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: return a clean model id from the OpenAI API instead of the local .gguf path (#6518)

Daniel Han9451aef51e26
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 255fc4140f4..31969afb14b 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -5476,6 +5476,15 @@ class LlamaCppBackend:
"--no-context-shift",
]
+ # Report a clean public model id (matching GET /v1/models) rather
+ # than the raw -m path in llama-server's own /v1/models and the
+ # "model" field of its chat/completions responses.
+ from core.inference.model_ids import public_model_id
+
+ _alias = public_model_id(self._model_identifier or model_path)
+ if _alias:
+ cmd.extend(["--alias", _alias])
+
fully_gpu_offloaded = False
if use_fit:
cmd.extend(["--fit", "on"])
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index b42be5ee0d0..f400d2ae406 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -25,6 +25,11 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
# Model identity: Studio resolves it from LoadRequest; a second -m would
# load a different model than Studio thinks it loaded.
frozenset({"-m", "--model"}),
+ # Public model id: Studio sets a sanitized --alias so the OpenAI API never
+ # exposes the local .gguf path. A user-supplied alias is appended after
+ # Studio's and, with llama.cpp's last-wins parsing, would reintroduce the
+ # path leak this is meant to prevent.
+ frozenset({"-a", "--alias"}),
frozenset({"-mu", "--model-url"}),
frozenset({"-dr", "--docker-repo"}),
frozenset({"-hf", "-hfr", "--hf-repo"}),
diff --git a/studio/backend/core/inference/model_ids.py b/studio/backend/core/inference/model_ids.py
new file mode 100644
index 00000000000..4d409cb4b54
--- /dev/null
+++ b/studio/backend/core/inference/model_ids.py
@@ -0,0 +1,57 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Public model identifiers for the OpenAI-compatible API.
+
+The exposed API must report a stable, clean model id rather than the absolute
+on-disk path of a local GGUF. The internal identifier for a direct local load is
+the absolute ``.gguf`` path, which leaks the host filesystem layout and is
+awkward for clients to round-trip. ``public_model_id`` maps such an internal
+identifier to a clean name while leaving Hugging Face repo ids (``org/model``)
+and already-clean names untouched.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Optional
+
+_GGUF_SUFFIX = ".gguf"
+
+
+def _looks_like_path(identifier: str) -> bool:
+ """True when *identifier* is a local filesystem path, not a HF repo id.
+
+ A repo id is ``org/model`` (a single forward slash, no leading separator, no
+ drive, no ``.gguf``). Anything ending in ``.gguf``, starting with a path
+ separator or a relative/home prefix (``./``, ``../``, ``~``), carrying a
+ Windows drive, or with three or more ``/`` segments is treated as a local
+ path.
+ """
+ if identifier.lower().endswith(_GGUF_SUFFIX):
+ return True
+ if identifier.startswith(("/", "\\", "./", "../", ".\\", "..\\", "~")):
+ return True
+ if len(identifier) >= 2 and identifier[1] == ":": # Windows drive, e.g. C:\
+ return True
+ if identifier.count("/") >= 2 or "\\" in identifier:
+ return True
+ return False
+
+
+def public_model_id(identifier: Optional[str]) -> Optional[str]:
+ """Return a clean, path-free public id for *identifier*.
+
+ - Local GGUF path -> the file stem with ``.gguf`` stripped, e.g.
+ ``/srv/models/Qwen3-30B-A3B-Q4_K_M.gguf`` -> ``Qwen3-30B-A3B-Q4_K_M``.
+ - HF repo id (``org/model``) and already-clean names -> returned unchanged.
+ - ``None`` / empty -> returned unchanged.
+ """
+ if not identifier:
+ return identifier
+ if not _looks_like_path(identifier):
+ return identifier
+ name = os.path.basename(identifier.replace("\\", "/").rstrip("/"))
+ if name.lower().endswith(_GGUF_SUFFIX):
+ name = name[: -len(_GGUF_SUFFIX)]
+ return name or identifier
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a9c85fa99ac..1061542ca65 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1107,6 +1107,7 @@ from auth.authentication import get_current_subject
from state.tool_approvals import resolve_tool_decision
from core.inference.key_exchange import decrypt_api_key
+from core.inference.model_ids import public_model_id
from core.inference.api_monitor import api_monitor
from core.inference.llama_http import nonstreaming_client
from core.inference.providers import get_base_url
@@ -3703,7 +3704,7 @@ async def generate_audio(
# Pick backend — both return (wav_bytes, sample_rate)
llama_backend = get_llama_cpp_backend()
if llama_backend.is_loaded and getattr(llama_backend, "_is_audio", False):
- model_name = llama_backend.model_identifier
+ model_name = public_model_id(llama_backend.model_identifier)
gen = lambda: llama_backend.generate_audio_response(
text = text,
audio_type = llama_backend._audio_type,
@@ -3721,7 +3722,7 @@ async def generate_audio(
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 = backend.active_model_name
+ model_name = public_model_id(backend.active_model_name)
gen = lambda: backend.generate_audio_response(
text = text,
temperature = payload.temperature,
@@ -4837,7 +4838,8 @@ async def openai_chat_completions(
return response
if using_gguf:
- model_name = llama_backend.model_identifier or payload.model
+ # Echo a clean public id in the response, never the absolute .gguf path.
+ model_name = public_model_id(llama_backend.model_identifier) or payload.model
if getattr(llama_backend, "_is_audio", False):
if _wants_multiple_choices(payload):
_raise_unsupported_n("GGUF audio chat completions")
@@ -4852,7 +4854,9 @@ async def openai_chat_completions(
status_code = 400,
detail = "No model loaded. Call POST /inference/load first.",
)
- model_name = backend.active_model_name or payload.model
+ # 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
if _wants_multiple_choices(payload):
_raise_unsupported_n("non-GGUF chat completions")
@@ -6401,7 +6405,9 @@ def _openai_model_objects() -> list[dict]:
llama_backend = get_llama_cpp_backend()
if llama_backend.is_loaded:
entry = {
- "id": llama_backend.model_identifier,
+ # Public id, never the absolute .gguf path (which leaks the host
+ # filesystem layout); see core.inference.model_ids.public_model_id.
+ "id": public_model_id(llama_backend.model_identifier),
"object": "model",
"created": _created,
"owned_by": "local",
@@ -6422,7 +6428,7 @@ def _openai_model_objects() -> list[dict]:
if backend.active_model_name:
model_info = backend.models.get(backend.active_model_name, {})
entry = {
- "id": backend.active_model_name,
+ "id": public_model_id(backend.active_model_name),
"object": "model",
"created": _created,
"owned_by": "local",
@@ -6463,9 +6469,24 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge
model, or 404 model_not_found otherwise. Defined after the LIST route so
it does not shadow it; ``{model_id:path}`` keeps ids with slashes intact.
"""
- for model in _openai_model_objects():
+ objects = _openai_model_objects()
+ for model in objects:
if model["id"] == model_id:
return model
+ # Backward compatibility: a client may still send the legacy raw identifier
+ # (e.g. an absolute .gguf path cached from an older /v1/models). Resolve it to
+ # the clean object so it keeps working, without ever echoing the path back.
+ llama_backend = get_llama_cpp_backend()
+ backend = get_inference_backend()
+ for raw in (
+ llama_backend.model_identifier if llama_backend.is_loaded else None,
+ backend.active_model_name or None,
+ ):
+ if raw and model_id == raw:
+ clean = public_model_id(raw)
+ for model in objects:
+ if model["id"] == clean:
+ return model
raise HTTPException(
status_code = 404,
detail = openai_error_body(
@@ -7402,6 +7423,15 @@ async def _responses_stream(
target_url = f"{llama_backend.base_url}/v1/chat/completions"
async def event_generator():
+ # Clean public id for every response envelope. Prefer the loaded model's
+ # id so the stream agrees with /v1/models, chat/completions and the
+ # non-streaming twin; fall back to a sanitized payload.model (a legacy
+ # raw .gguf path is stripped, never echoed back).
+ _clean_model = (
+ public_model_id(getattr(llama_backend, "model_identifier", None))
+ or public_model_id(payload.model)
+ or payload.model
+ )
full_text = ""
full_reasoning = ""
input_tokens = 0
@@ -7563,7 +7593,7 @@ async def _responses_stream(
"object": "response",
"created_at": created_at,
"status": "failed",
- "model": payload.model,
+ "model": _clean_model,
"output": _snapshot_output(),
"usage": {
"input_tokens": input_tokens,
@@ -7587,7 +7617,7 @@ async def _responses_stream(
"object": "response",
"created_at": created_at,
"status": "in_progress",
- "model": payload.model,
+ "model": _clean_model,
"output": [],
"usage": {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0},
},
@@ -7627,7 +7657,7 @@ async def _responses_stream(
"object": "response",
"created_at": created_at,
"status": "failed",
- "model": payload.model,
+ "model": _clean_model,
"output": [],
"error": {"code": 502, "message": _friendly_error(e)},
},
@@ -7653,7 +7683,7 @@ async def _responses_stream(
"object": "response",
"created_at": created_at,
"status": "failed",
- "model": payload.model,
+ "model": _clean_model,
"output": [],
"error": {
"code": resp.status_code,
@@ -8002,7 +8032,7 @@ async def _responses_stream(
"object": "response",
"created_at": created_at,
"status": "completed",
- "model": payload.model,
+ "model": _clean_model,
"output": _snapshot_output(),
"usage": {
"input_tokens": input_tokens,
@@ -8274,7 +8304,13 @@ async def anthropic_messages(
),
)
- model_name = getattr(llama_backend, "model_identifier", None) or payload.model
+ # Clean public id so /v1/messages never echoes the local .gguf path (and a
+ # legacy raw path sent as payload.model is sanitized rather than returned).
+ model_name = (
+ public_model_id(getattr(llama_backend, "model_identifier", None))
+ or public_model_id(payload.model)
+ or payload.model
+ )
message_id = f"msg_{uuid.uuid4().hex[:24]}"
# ── Translate Anthropic → OpenAI ──────────────────────────
diff --git a/studio/backend/tests/test_model_ids.py b/studio/backend/tests/test_model_ids.py
new file mode 100644
index 00000000000..1b0cd927d8f
--- /dev/null
+++ b/studio/backend/tests/test_model_ids.py
@@ -0,0 +1,53 @@
+# 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 sys
+from pathlib import Path
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from core.inference.model_ids import public_model_id # noqa: E402
+
+
+def test_local_gguf_path_becomes_clean_stem():
+ assert public_model_id("/srv/models/Qwen3-30B-A3B-Q4_K_M.gguf") == "Qwen3-30B-A3B-Q4_K_M"
+ assert public_model_id("/home/u/.cache/models/llama.gguf") == "llama"
+
+
+def test_hf_repo_id_unchanged():
+ assert public_model_id("unsloth/Qwen3-30B-A3B-GGUF") == "unsloth/Qwen3-30B-A3B-GGUF"
+ assert public_model_id("Qwen3-30B-A3B") == "Qwen3-30B-A3B"
+
+
+def test_none_and_empty_passthrough():
+ assert public_model_id(None) is None
+ assert public_model_id("") == ""
+
+
+def test_windows_path():
+ assert public_model_id("C:\\models\\foo.gguf") == "foo"
+ assert public_model_id("models\\sub\\bar.gguf") == "bar"
+
+
+def test_directory_path_uses_basename():
+ assert public_model_id("/opt/models/MyModelDir") == "MyModelDir"
+ # A 3+ segment relative path is a local path, not an org/model repo id.
+ assert public_model_id("a/b/c") == "c"
+
+
+def test_relative_and_home_paths_are_sanitized():
+ # ./ ../ ~ prefixed paths are local and must not be echoed raw.
+ assert public_model_id("./model.gguf") == "model"
+ assert public_model_id("../models/foo.gguf") == "foo"
+ assert public_model_id("~/models/baz.gguf") == "baz"
+ assert public_model_id("./mistral") == "mistral"
+ assert public_model_id("~/mistral") == "mistral"
+ assert public_model_id(".\\models\\foo.gguf") == "foo"
+
+
+def test_dotted_repo_id_not_mistaken_for_relative_path():
+ # A leading dot that is not ./ or ../ is an ordinary clean name.
+ assert public_model_id(".hidden-model") == ".hidden-model"
+ assert public_model_id("org/.config") == "org/.config"
diff --git a/studio/backend/tests/test_openai_models_path_leak.py b/studio/backend/tests/test_openai_models_path_leak.py
new file mode 100644
index 00000000000..a84a33f8402
--- /dev/null
+++ b/studio/backend/tests/test_openai_models_path_leak.py
@@ -0,0 +1,45 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""GET /v1/models must report a clean public id, never the on-disk .gguf path."""
+
+import json
+import sys
+from pathlib import Path
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import routes.inference as inf # noqa: E402
+
+
+class _FakeLlama:
+ is_loaded = True
+ model_identifier = "/srv/models/Qwen3-30B-A3B-Q4_K_M.gguf"
+ context_length = 4096
+ max_context_length = None
+ native_context_length = None
+
+
+class _FakeUnsloth:
+ active_model_name = None
+ models: dict = {}
+ context_length = None
+ max_seq_length = None
+
+
+def test_openai_models_returns_clean_id_without_path(monkeypatch):
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama())
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _FakeUnsloth())
+
+ objs = inf._openai_model_objects()
+
+ assert len(objs) == 1
+ assert objs[0]["id"] == "Qwen3-30B-A3B-Q4_K_M"
+ # The serialized payload must not leak the absolute path or the .gguf suffix.
+ blob = json.dumps(objs)
+ assert "/srv/models" not in blob
+ assert ".gguf" not in blob
+ # Context fields still flow through.
+ assert objs[0]["context_length"] == 4096