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: import HfApi on first use instead of at backend start (#17273)
Daniel Hanf40d2b19aced
diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pyindex f78fd604a2a..c0a73931d74 100644--- a/studio/backend/hub/services/models/account_access.py+++ b/studio/backend/hub/services/models/account_access.py@@ -22,7 +22,7 @@ from pathlib import Pathfrom fastapi import HTTPExceptionfrom fastapi.responses import JSONResponse-from huggingface_hub import HfApi, constants as hf_constants+from huggingface_hub import constants as hf_constantsfrom auth import policyfrom core.inference.gpu_arbiter import GpuBusyForAnotherAccountError@@ -40,6 +40,20 @@ from utils.account_context import (is_owner_context,)++def __getattr__(name):+ # Lazy (~0.2 s at boot); from the submodule so a patched huggingface_hub.HfApi is never cached.+ if name == "HfApi":+ from huggingface_hub.hf_api import HfApi+ globals()["HfApi"] = HfApi+ return HfApi+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+++def _hf_api(*args, **kwargs):+ return (globals().get("HfApi") or __getattr__("HfApi"))(*args, **kwargs)++_ACCOUNT_ID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")@@ -572,7 +586,7 @@ def _hub_public_answer() -> bool | None:"""True when the Hub says public, False for private/gated/missing, None when unaskable."""try:- info = HfApi(endpoint = endpoint).repo_info(+ info = _hf_api(endpoint = endpoint).repo_info(repo_id, repo_type = repo_type, token = False, timeout = 5.0)except Exception as exc: # noqa: BLE001 - classified below, never trusted as public@@ -1076,7 +1090,7 @@ def authorize_download(repo_id: str, repo_type: str, hf_token) -> None:detail = "Only the installation owner can download while ModelScope is the model source",)try:- api = HfApi()+ api = _hf_api()token = account_hf_token(hf_token)info = api.repo_info(repo_id, repo_type = repo_type, token = token, timeout = 5.0)if getattr(info, "gated", False):diff --git a/studio/backend/tests/test_hf_api_lazy_import.py b/studio/backend/tests/test_hf_api_lazy_import.pynew file mode 100644index 00000000000..52703a5f5f3--- /dev/null+++ b/studio/backend/tests/test_hf_api_lazy_import.py@@ -0,0 +1,24 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The account and token-validation modules import HfApi (huggingface_hub.hf_api) on first use, not at boot."""++import subprocess+import sys+from pathlib import Path++BACKEND = Path(__file__).resolve().parents[1]+++def test_boot_modules_do_not_import_hf_api():+ code = (+ "import sys\n"+ f"sys.path.insert(0, {str(BACKEND)!r})\n"+ "import hub.services.models.account_access as access, utils.hf_token_validation\n"+ "assert 'huggingface_hub.hf_api' not in sys.modules\n"+ "import huggingface_hub\n"+ "huggingface_hub.HfApi = object\n"+ "assert access.HfApi.__module__ == 'huggingface_hub.hf_api'\n"+ )+ out = subprocess.run([sys.executable, "-c", code], capture_output = True, text = True, timeout = 300)+ assert out.returncode == 0, out.stderr[-3000:]diff --git a/studio/backend/utils/hf_token_validation.py b/studio/backend/utils/hf_token_validation.pyindex b5a79dd2230..9613bf36de8 100644--- a/studio/backend/utils/hf_token_validation.py+++ b/studio/backend/utils/hf_token_validation.py@@ -15,7 +15,6 @@ from typing import Literalfrom utils.account_context import current_account_idfrom utils.hub_settings import MODELSCOPE, active_source, hugging_face_endpoint-from huggingface_hub import HfApifrom huggingface_hub.utils import build_hf_headers, get_session@@ -153,7 +152,11 @@ def validate_hf_token(token: str, *, rate_key: str) -> TokenValidationResult:return TokenValidationResult(status = "invalid")account_id = current_account_id()# Per endpoint: a token one Hub rejects may be another's. The ModelScope adapter has no whoami.- endpoint = hugging_face_endpoint() if active_source() == MODELSCOPE else HfApi().endpoint+ if active_source() == MODELSCOPE:+ endpoint = hugging_face_endpoint()+ else:+ from huggingface_hub.hf_api import HfApi+ endpoint = HfApi().endpointtoken_fingerprint = (account_id, _fingerprint(normalized), endpoint.rstrip("/"))account_rate_key = (account_id, rate_key)owner_event: threading.Event | None = None