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: forward llama-server /metrics, /slots, /tokenize and /detokenize (#13354)
Daniel Han1201351b90b4
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex a1d7c0bd77a..cff05fccf0b 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1405,6 +1405,9 @@ _BODY_PROTECTED_PREFIXES = (# Unauthenticated (login, refresh): every route takes a few hundred bytes of JSON."/api/auth","/mcp",+ # llama-server passthrough POSTs; keyless inference scope admits them.+ "/tokenize",+ "/detokenize",# Everything else under /api. FastAPI reads a body before the route's auth dependency runs, so an unlisted# prefix let an unauthenticated client stream an unbounded body into memory."/api/",diff --git a/studio/backend/routes/llama_compat.py b/studio/backend/routes/llama_compat.pyindex 3d1f08b17f1..310cbf0d1a0 100644--- a/studio/backend/routes/llama_compat.py+++ b/studio/backend/routes/llama_compat.py@@ -5,8 +5,9 @@Probes for engine endpoints used to land on main.py's SPA catch-all, so ``GET /props`` returned 200 and a pageof HTML. That is worse than a 404: a probe reads the status before the body. Served here: ``/props``,-``/v1/props``, ``/version``. Everything else in llama-server's table gets an explicit 404, on its real method as-well as GET.+``/v1/props``, ``/version``, plus a passthrough to the resident llama-server for ``GET /metrics``, ``GET /slots``,+``POST /tokenize`` and ``POST /detokenize`` (#11705), owner only. Everything else in llama-server's table gets an+explicit 404, on its real method as well as GET.Deliberately NOT served: Ollama's ``/api/tags`` and ``/api/show``. Answering them makes a client select Ollamaand then fail on ``/api/chat``, which Studio does not implement; the reporting user's client instead fell back@@ -19,7 +20,9 @@ import asyncioimport functoolsfrom typing import Any, Optional-from fastapi import APIRouter, Depends, HTTPException+import httpx+from fastapi import APIRouter, Depends, HTTPException, Request+from fastapi.responses import JSONResponse, Responsefrom auth.authentication import get_current_subjectfrom loggers import get_logger@@ -64,6 +67,17 @@ _ENGINE_PROBE_PATHS = frozenset(# /slots/:id_slot is the one dynamic entry in that table, and Studio calls it itself._ENGINE_PROBE_PREFIXES = ("slots/",)+# Forwarded to the resident llama-server (#11705). Slot save / restore stays denied: Studio owns slot persistence.+_PASSTHROUGH_ROUTES = frozenset(+ {+ ("GET", "metrics"),+ ("GET", "slots"),+ ("POST", "tokenize"),+ ("POST", "detokenize"),+ }+)+_PASSTHROUGH_TIMEOUT_S = 30.0+# The /v1 entries Studio does not implement. A test asserts each is really absent from# the assembled app, so implementing one fails CI instead of being shadowed by a 404._UNSERVED_V1_PROBE_PATHS = frozenset(@@ -143,9 +157,10 @@ def _server_props() -> dict:# flags in the payload).for _child_only in ("ui", "ui_settings", "cors_proxy_enabled"):props.pop(_child_only, None)- props["endpoint_slots"] = Falseprops["endpoint_props"] = False- props["endpoint_metrics"] = False+ passthrough = llama_loaded and not _caller_is_managed_account()+ props["endpoint_slots"] = passthrough and props.get("endpoint_slots") is True+ props["endpoint_metrics"] = passthrough and props.get("endpoint_metrics") is True# Only when llama-server owns the resident model: with MLX loaded, reading the# unloaded llama backend describes a serving model as having no context or slots.@@ -196,6 +211,76 @@ def _resident_hidden_from_caller() -> bool:return bool(slot) and account_access.resident_hidden("chat", slot)+def _caller_is_managed_account() -> bool:+ from hub.services.models import account_access+ return account_access.managed_account()+++def _upstream_client() -> httpx.AsyncClient:+ # verify=False: plain HTTP to loopback, skips loading the CA bundle per call (~35 ms).+ return httpx.AsyncClient(trust_env = False, verify = False)+++def _engine_error(status_code: int, message: str) -> JSONResponse:+ error_type = "unavailable_error" if status_code == 503 else "not_found_error"+ return JSONResponse(+ status_code = status_code,+ content = {"error": {"code": status_code, "message": message, "type": error_type}},+ )+++async def _forward_to_llama_server(request: Request, path: str) -> Response:+ # Owner only: /slots and /metrics are server-wide, not scoped per account.+ if await asyncio.to_thread(_caller_is_managed_account):+ return _engine_error(404, "API endpoint not found")+ llama_backend = _inference().get_llama_cpp_backend()+ # Unload flips is_loaded before clearing _port; "127.0.0.1:None" raises InvalidURL, not HTTPError.+ port = getattr(llama_backend, "_port", None)+ if not getattr(llama_backend, "is_loaded", False) or not port:+ return _engine_error(503, "No llama.cpp model is loaded")+ url = f"http://127.0.0.1:{port}/{path}"+ headers = dict(llama_backend._auth_headers or {})+ body = await request.body() if request.method == "POST" else None+ if body is not None:+ headers["Content-Type"] = request.headers.get("content-type", "application/json")+ try:+ async with _upstream_client() as client:+ upstream = await client.request(+ request.method,+ url,+ params = request.query_params,+ content = body,+ headers = headers,+ timeout = _PASSTHROUGH_TIMEOUT_S,+ )+ except httpx.HTTPError as exc:+ logger.info("llama-server passthrough %s /%s failed: %s", request.method, path, exc)+ return _engine_error(503, "llama.cpp server is not reachable")+ return Response(+ content = upstream.content,+ status_code = upstream.status_code,+ media_type = upstream.headers.get("content-type"),+ )+++def _make_passthrough(path: str):+ async def passthrough(request: Request, current_subject: str = Depends(get_current_subject)):+ return await _forward_to_llama_server(request, path)++ passthrough.__name__ = f"llama_passthrough_{path}"+ return passthrough+++for _method, _path in sorted(_PASSTHROUGH_ROUTES):+ for _form in (f"/{_path}", f"/{_path}/"):+ router.add_api_route(+ _form,+ _make_passthrough(_path),+ methods = [_method],+ include_in_schema = False,+ )++@router.get("/version", include_in_schema = False)@router.get("/version/", include_in_schema = False)async def studio_version(current_subject: str = Depends(get_current_subject)):@@ -220,12 +305,16 @@ def _both_forms(path: str) -> tuple:return (path, path + "/")+def _denied_methods(path: str) -> list:+ return [m for m in _PROBE_DENIED_METHODS if (m, path) not in _PASSTHROUGH_ROUTES]++for _probe_path in sorted(_ENGINE_PROBE_PATHS):for _form in _both_forms(f"/{_probe_path}"):router.add_api_route(_form,_probe_not_found,- methods = _PROBE_DENIED_METHODS,+ methods = _denied_methods(_probe_path),include_in_schema = False,)@@ -254,6 +343,8 @@ def add_get_denials(app) -> None:none, so these paths matched on method alone and answered 405, which a client reads as "endpoint exists"."""for path in sorted(_ENGINE_PROBE_PATHS) + sorted(_UNSERVED_V1_PROBE_PATHS):+ if ("GET", path) in _PASSTHROUGH_ROUTES:+ continuefor form in _both_forms(f"/{path}"):app.add_api_route(form, _probe_not_found, methods = ["GET"], include_in_schema = False)for form in _both_forms("/slots/{id_slot}"):diff --git a/studio/backend/tests/test_llama_compat_routes.py b/studio/backend/tests/test_llama_compat_routes.pyindex e76ee8c6af0..7845fecd789 100644--- a/studio/backend/tests/test_llama_compat_routes.py+++ b/studio/backend/tests/test_llama_compat_routes.py@@ -71,6 +71,8 @@ class _Backend:self.context_length = 262144self.chat_template = "{{ messages }}"self._props = props+ self._port = 52345+ self._auth_headers = {"Authorization": "Bearer child-key"}def _query_server_props(self):return self._props@@ -188,7 +190,7 @@ def test_the_html_fallback_is_what_used_to_answer_these():def test_engine_endpoints_studio_does_not_serve_are_404_not_html():mod = _load()with _client(mod) as c:- for path in ("/slots", "/completion", "/metrics", "/tokenize", "/health"):+ for path in ("/completion", "/tokenize", "/detokenize", "/health"):r = c.get(path)assert r.status_code == 404, pathassert "text/html" not in r.headers.get("content-type", ""), path@@ -339,9 +341,9 @@ def test_the_version_lookup_is_resolved_once(monkeypatch):def test_a_real_asset_wins_over_the_probe_deny_list(tmp_path):- """The guard runs after the static lookup, so a shipped file named `metrics` wins."""+ """The guard runs after the static lookup, so a shipped file named `health` wins."""mod = _load()- (tmp_path / "metrics").write_text("asset-body")+ (tmp_path / "health").write_text("asset-body")app = FastAPI()app.include_router(mod.router)@@ -356,8 +358,30 @@ def test_a_real_asset_wins_over_the_probe_deny_list(tmp_path):app.dependency_overrides[mod.get_current_subject] = lambda: "test"with TestClient(app) as c:- assert c.get("/metrics").text == "asset-body"- assert c.get("/slots").status_code == 404+ assert c.get("/health").text == "asset-body"+ assert c.get("/completion").status_code == 404+++def test_no_ui_route_or_public_asset_takes_a_forwarded_get_path():+ """These GET routes sit ahead of the SPA catch-all, so a page or asset by that name would be shadowed."""+ frontend = _BACKEND.parent / "frontend"+ if not frontend.is_dir():+ pytest.skip("frontend sources not present in this checkout")+ mod = _load()+ forwarded = {path for method, path in mod._PASSTHROUGH_ROUTES if method == "GET"}+ public = (+ {p.name.lower() for p in (frontend / "public").iterdir()}+ if (frontend / "public").is_dir()+ else set()+ )+ declared = set()+ for path in (frontend / "src" / "app" / "routes").glob("*.tsx"):+ for line in path.read_text(encoding = "utf-8").splitlines():+ line = line.strip()+ if line.startswith('path: "') and line.endswith('",'):+ declared.add(line[len('path: "') : -2].strip("/").lower())+ assert not forwarded & public, forwarded & public+ assert not forwarded & declared, forwarded & declareddef test_no_client_side_ui_route_is_shadowed_by_the_deny_list():@@ -400,8 +424,6 @@ def test_the_ollama_surface_is_not_advertised():"path",["/completion",- "/tokenize",- "/detokenize","/rerank","/infill","/embedding",@@ -454,6 +476,10 @@ def test_the_probe_paths_are_admitted_under_keyless_inference_scope():# Not the Ollama paths: they are not served at all.for path in ("/api/tags", "/api/show", "/api/version"):assert ("GET", path) not in _INFERENCE_ROUTES, path+ for path in ("/tokenize", "/detokenize"):+ assert ("POST", path) in _INFERENCE_ROUTES, path+ for path in ("/slots", "/metrics"):+ assert ("GET", path) not in _INFERENCE_ROUTES, path# ── round two ─────────────────────────────────────────────────────────────────@@ -546,9 +572,7 @@ def test_a_bare_llama_route_404s_on_every_method_a_client_would_use():assert "text/html" not in r.headers.get("content-type", ""), (method, path)-def test_props_does_not_advertise_child_endpoints_studio_denies():- """tools/server/server-context.cpp puts all three flags in the payload, and Studio- launches with --metrics, so endpoint_metrics arrived true while /metrics 404s here."""+def test_props_advertises_only_the_child_endpoints_studio_forwards():upstream = {"endpoint_slots": True,"endpoint_props": True,@@ -561,25 +585,218 @@ def test_props_does_not_advertise_child_endpoints_studio_denies():mod = _load(backend = _Backend(props = upstream))with _client(mod) as c:body = c.get("/props").json()- assert body["endpoint_slots"] is False+ assert body["endpoint_slots"] is Trueassert body["endpoint_props"] is False- assert body["endpoint_metrics"] is False+ assert body["endpoint_metrics"] is Truefor child_only in ("ui", "ui_settings", "cors_proxy_enabled"):assert child_only not in body, child_only# The fields that do describe the model still come through untouched.assert body["total_slots"] == 4-def test_the_denied_endpoints_props_advertises_really_are_denied():- """Every flag set False above names a path that really 404s."""+def test_props_does_not_advertise_endpoints_the_child_has_off():+ upstream = {"endpoint_slots": False, "endpoint_metrics": False}+ mod = _load(backend = _Backend(props = upstream))+ with _client(mod) as c:+ body = c.get("/props").json()+ assert body["endpoint_slots"] is False+ assert body["endpoint_metrics"] is False+++def test_props_does_not_advertise_forwarded_endpoints_with_nothing_loaded():+ mod = _load(backend = _Backend(loaded = False, props = {"endpoint_metrics": True}))+ with _client(mod) as c:+ body = c.get("/props").json()+ assert body["endpoint_slots"] is False+ assert body["endpoint_metrics"] is False+++def test_props_does_not_advertise_forwarded_endpoints_to_a_managed_account(monkeypatch):+ mod = _load(backend = _Backend(props = {"endpoint_slots": True, "endpoint_metrics": True}))+ monkeypatch.setattr(mod, "_caller_is_managed_account", lambda: True)+ monkeypatch.setattr(mod, "_resident_hidden_from_caller", lambda: False)+ with _client(mod) as c:+ body = c.get("/props").json()+ assert body["endpoint_slots"] is False+ assert body["endpoint_metrics"] is False+++def test_post_props_is_still_not_served():mod = _load()with _client(mod) as c:- for path in ("/slots", "/metrics"):- assert c.get(path).status_code == 404, path- # POST /props is llama-server's props-change endpoint; Studio serves GET only.assert c.post("/props", json = {}).status_code in (404, 405)+class _Upstream:+ def __init__(self, *, fail = False):+ self.calls = []+ self.fail = fail++ def handler(self, request):+ import httpx++ self.calls.append(request)+ if self.fail:+ raise httpx.ConnectError("connection refused", request = request)+ path = request.url.path+ if path == "/metrics":+ return httpx.Response(+ 200,+ content = b"llamacpp:prompt_tokens_total 12\n",+ headers = {"content-type": "text/plain; version=0.0.4"},+ )+ if path == "/slots":+ return httpx.Response(200, json = [{"id": 0, "is_processing": False}])+ if path == "/tokenize":+ return httpx.Response(200, json = {"tokens": [9906, 1917]})+ if path == "/detokenize":+ return httpx.Response(200, json = {"content": "Hello world"})+ return httpx.Response(404, json = {"error": "not found"})+++def _with_upstream(monkeypatch, mod, upstream):+ import httpx+ monkeypatch.setattr(+ mod,+ "_upstream_client",+ lambda: httpx.AsyncClient(transport = httpx.MockTransport(upstream.handler)),+ )+++ "method, path, expect",+ [+ ("GET", "/slots", [{"id": 0, "is_processing": False}]),+ ("POST", "/tokenize", {"tokens": [9906, 1917]}),+ ("POST", "/detokenize", {"content": "Hello world"}),+ ],+)+def test_the_forwarded_endpoints_reach_the_child_with_its_key(monkeypatch, method, path, expect):+ import json++ mod = _load()+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _client(mod) as c:+ r = c.request(method, path, json = {"content": "Hello world"} if method == "POST" else None)+ assert r.status_code == 200, r.text+ assert r.json() == expect+ (sent,) = upstream.calls+ assert sent.method == method+ assert str(sent.url) == "http://127.0.0.1:52345" + path+ assert sent.headers["authorization"] == "Bearer child-key"+ if method == "POST":+ assert json.loads(sent.content) == {"content": "Hello world"}+ assert sent.headers["content-type"].startswith("application/json")+++def test_metrics_reaches_the_child_and_keeps_the_prometheus_content_type(monkeypatch):+ mod = _load()+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _client(mod) as c:+ r = c.get("/metrics")+ assert r.status_code == 200+ assert r.content == b"llamacpp:prompt_tokens_total 12\n"+ assert r.headers["content-type"].startswith("text/plain"), r.headers["content-type"]+ assert upstream.calls[0].headers["authorization"] == "Bearer child-key"+++def test_the_slash_form_is_forwarded_too(monkeypatch):+ mod = _load()+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _client(mod) as c:+ assert c.post("/tokenize/", json = {"content": "x"}).status_code == 200+ assert c.get("/metrics/").status_code == 200+ assert [r.url.path for r in upstream.calls] == ["/tokenize", "/metrics"]+++def test_the_query_string_is_forwarded(monkeypatch):+ mod = _load()+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _client(mod) as c:+ c.get("/slots?fail_on_no_slot=1")+ assert upstream.calls[0].url.params["fail_on_no_slot"] == "1"+++def test_nothing_loaded_is_503_in_llama_servers_error_shape(monkeypatch):+ mod = _load(backend = _Backend(loaded = False))+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _client(mod) as c:+ r = c.post("/tokenize", json = {"content": "x"})+ assert r.status_code == 503+ assert r.json()["error"]["code"] == 503+ assert upstream.calls == []+++def test_an_unload_racing_the_request_is_503_not_500(monkeypatch):+ """unload_model flips is_loaded before it clears _port."""+ backend = _Backend()+ backend._port = None+ mod = _load(backend = backend)+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _client(mod) as c:+ r = c.get("/slots")+ assert r.status_code == 503+ assert upstream.calls == []+++def test_an_unreachable_child_is_503_not_500(monkeypatch):+ mod = _load()+ _with_upstream(monkeypatch, mod, _Upstream(fail = True))+ with _client(mod) as c:+ r = c.get("/metrics")+ assert r.status_code == 503+ assert "text/html" not in r.headers.get("content-type", "")+++def test_a_managed_account_gets_the_404_and_the_child_is_never_asked(monkeypatch):+ mod = _load()+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ monkeypatch.setattr(mod, "_caller_is_managed_account", lambda: True)+ with _client(mod) as c:+ for method, path in (("GET", "/metrics"), ("GET", "/slots"), ("POST", "/tokenize")):+ r = c.request(method, path, json = {} if method == "POST" else None)+ assert r.status_code == 404, (method, path, r.status_code)+ assert upstream.calls == []+++ "method, path",+ [+ ("POST", "/slots"),+ ("POST", "/slots/0"),+ ("DELETE", "/slots/0"),+ ("POST", "/metrics"),+ ("GET", "/tokenize"),+ ("PUT", "/detokenize"),+ ],+)+def test_only_the_read_only_methods_are_forwarded(monkeypatch, method, path):+ mod = _load()+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _client(mod) as c:+ r = c.request(method, path, json = {} if method in ("POST", "PUT") else None)+ assert r.status_code == 404, (method, path, r.status_code)+ assert upstream.calls == []+++def test_the_forwarded_gets_survive_api_only_mode(monkeypatch):+ mod = _load()+ upstream = _Upstream()+ _with_upstream(monkeypatch, mod, upstream)+ with _api_only_client(mod) as c:+ assert c.get("/metrics").status_code == 200+ assert c.get("/slots").status_code == 200+ assert c.get("/health").status_code == 404++# ── round three ───────────────────────────────────────────────────────────────@@ -787,7 +1004,7 @@ def test_the_slash_form_of_a_denied_path_404s_rather_than_405(method, path):@pytest.mark.parametrize("path",- ["/completion", "/completion/", "/health", "/metrics", "/slots", "/v1/health", "/slots/3"],+ ["/completion", "/completion/", "/health", "/tokenize", "/v1/health", "/slots/3"],)def test_a_get_probe_404s_in_api_only_mode(path):"""--api-only mounts no frontend, so the catch-all that supplies the GET 404 is notdiff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex d87ba4ea73c..56a05d42418 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -397,6 +397,28 @@ class TestMaxBodyMiddleware:):assert any(path.startswith(p) for p in main_module._BODY_PROTECTED_PREFIXES), path+ def test_llama_passthrough_posts_are_capped(self, main_module):+ from fastapi import Request+ from fastapi.testclient import TestClient++ for path in ("/tokenize", "/tokenize/", "/detokenize", "/detokenize/"):+ assert any(path.startswith(p) for p in main_module._BODY_PROTECTED_PREFIXES), path++ app = FastAPI()+ app.add_middleware(+ main_module.MaxBodyMiddleware,+ max_bytes_getter = lambda: 64,+ protected_prefixes = main_module._BODY_PROTECTED_PREFIXES,+ )++ @app.post("/tokenize")+ async def _tokenize(request: Request):+ return {"n": len(await request.body())}++ with TestClient(app) as c:+ assert c.post("/tokenize", content = b"x" * 64).status_code == 200+ assert c.post("/tokenize", content = b"x" * 65).status_code == 413+def test_upload_passthrough_rejects_declared_body_over_dedicated_cap(self, main_module):app = _make_protected_app(128,diff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.pyindex 839db8abf2f..03b6d32e7f0 100644--- a/studio/backend/utils/keyless_api_access.py+++ b/studio/backend/utils/keyless_api_access.py@@ -45,6 +45,9 @@ _INFERENCE_ROUTES = frozenset(("GET", "/props"),("GET", "/v1/props"),("GET", "/version"),+ # Token counters, like /v1/chat/count_tokens. Not /slots or /metrics: those are server-wide.+ ("POST", "/tokenize"),+ ("POST", "/detokenize"),})