Skip to content

studio: list the full local model catalog from /v1/models - #6519

Merged
oobabooga merged 14 commits into
mainfrom
studio-v1-models-catalog
Jun 26, 2026
Merged

oobabooga merged 14 commits into
mainfrom
studio-v1-models-catalog

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

/v1/models returned only the currently loaded model, so an OpenAI-compatible client could not discover the other models available on the server.

Change

  • Extracted a shared collect_local_models() scan (models directory, HF cache, and the other existing sources) and built the OpenAI list from it, marking the loaded entry, with a short cache.
  • /v1/models/{id} resolves against the full catalog.

Validation

  • test_openai_catalog.py.
  • Live: /v1/models returns the full catalog (264 entries in the test environment) with clean ids and no filesystem paths.

Note

Stacked on #6518 (uses its public_model_id helper for clean ids). The base branch of this PR is studio-model-id-sanitizer; please merge #6518 first.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a clean public model ID mapping utility to prevent absolute local paths from leaking through the OpenAI-compatible API, and refactors the local model scanning logic into a reusable collect_local_models function to populate the full catalog for GET /v1/models. The reviewer's feedback highlights a critical performance issue: executing these heavy synchronous filesystem scans directly within the FastAPI event loop blocks concurrent requests and active inference streams. The reviewer suggests making the catalog retrieval asynchronous, offloading the blocking I/O to a thread pool using asyncio.to_thread, and simplifying the backward compatibility checks.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +6129 to +6183
# Brief cache for the local-model filesystem scan so repeated /v1/models calls
# don't rescan the HF cache and models dirs on every request.
_CATALOG_CACHE: dict = {"at": 0.0, "models": []}
_CATALOG_TTL_S = 30.0


def _cached_local_catalog() -> list:
"""Locally available models (models dir + HF caches + LM Studio + scan
folders), cached for a few seconds. Returns a list of LocalModelInfo."""
now = time.monotonic()
if not _CATALOG_CACHE["models"] or (now - _CATALOG_CACHE["at"]) > _CATALOG_TTL_S:
try:
from pathlib import Path as _Path

from routes.models import collect_local_models

_CATALOG_CACHE["models"] = collect_local_models(_Path("./models").resolve())
except Exception as exc:
logger.debug("model catalog scan failed: %s", exc)
_CATALOG_CACHE["models"] = []
_CATALOG_CACHE["at"] = now
return _CATALOG_CACHE["models"]


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
scanning. Loaded entries keep their context fields and are marked
``loaded: true``. All ids are clean public ids (never absolute paths)."""
from core.inference.model_ids import public_model_id

_created = int(time.time())
# Loaded models first (clean ids + context fields), marked loaded.
by_id: dict[str, dict] = {}
for entry in _openai_model_objects():
by_id[entry["id"]] = {**entry, "loaded": True}

# Locally available (downloaded/cached) models that are not already loaded.
for info in _cached_local_catalog():
cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))
if not cid or cid in by_id:
continue
obj = {
"id": cid,
"object": "model",
"created": _created,
"owned_by": "local",
"loaded": False,
}
display = getattr(info, "display_name", None)
if display:
obj["display_name"] = display
by_id[cid] = obj

return list(by_id.values())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The collect_local_models function performs heavy synchronous filesystem operations (scanning multiple directories, checking file stats, etc.). Calling it directly within the event loop thread blocks all other concurrent requests, including active inference streams. Making _cached_local_catalog and _openai_catalog_objects asynchronous and running the blocking I/O in a thread pool using asyncio.to_thread prevents event loop starvation. Additionally, using an asyncio.Lock prevents redundant concurrent scans when multiple requests hit the endpoint simultaneously.

_CATALOG_CACHE: dict = {"at": 0.0, "models": []}
_CATALOG_TTL_S = 30.0
_CATALOG_LOCK = asyncio.Lock()


async def _cached_local_catalog() -> list:
    """Locally available models (models dir + HF caches + LM Studio + scan
    folders), cached for a few seconds. Returns a list of LocalModelInfo."""
    now = time.monotonic()
    if not _CATALOG_CACHE["models"] or (now - _CATALOG_CACHE["at"]) > _CATALOG_TTL_S:
        async with _CATALOG_LOCK:
            now = time.monotonic()
            if not _CATALOG_CACHE["models"] or (now - _CATALOG_CACHE["at"]) > _CATALOG_TTL_S:
                try:
                    from pathlib import Path as _Path

                    from routes.models import collect_local_models

                    _CATALOG_CACHE["models"] = await asyncio.to_thread(
                        collect_local_models, _Path("./models").resolve()
                    )
                except Exception as exc:
                    logger.debug("model catalog scan failed: %s", exc)
                    _CATALOG_CACHE["models"] = []
                _CATALOG_CACHE["at"] = now
    return _CATALOG_CACHE["models"]


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
    scanning. Loaded entries keep their context fields and are marked
    loaded: true. All ids are clean public ids (never absolute paths)."""
    from core.inference.model_ids import public_model_id

    _created = int(time.time())
    # Loaded models first (clean ids + context fields), marked loaded.
    by_id: dict[str, dict] = {}
    for entry in _openai_model_objects():
        by_id[entry["id"]] = {**entry, "loaded": True}

    # Locally available (downloaded/cached) models that are not already loaded.
    for info in await _cached_local_catalog():
        cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))
        if not cid or cid in by_id:
            continue
        obj = {
            "id": cid,
            "object": "model",
            "created": _created,
            "owned_by": "local",
            "loaded": False,
        }
        display = getattr(info, "display_name", None)
        if display:
            obj["display_name"] = display
        by_id[cid] = obj

    return list(by_id.values())

Comment thread studio/backend/routes/inference.py Outdated
memory. Each entry carries a clean public id and a ``loaded`` flag.
"""
return {"object": "list", "data": _openai_model_objects()}
return {"object": "list", "data": _openai_catalog_objects()}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Since _openai_catalog_objects is now an asynchronous function, it must be awaited.

Suggested change
return {"object": "list", "data": _openai_catalog_objects()}
return {"object": "list", "data": await _openai_catalog_objects()}

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +6210 to +6227
objects = _openai_catalog_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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Since _openai_catalog_objects is now asynchronous, it must be awaited. Additionally, the backward compatibility check can be significantly simplified and made more robust by checking if the requested model_id matches either the clean public ID or the raw ID directly against the full catalog. This avoids redundant calls to the inference backends and correctly handles available but currently unloaded models.

Suggested change
objects = _openai_catalog_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
objects = await _openai_catalog_objects()
for model in objects:
if model["id"] == model_id or model["id"] == public_model_id(model_id):
return model

reverse = True,
)
models = [m for m in models if not _is_hidden_model(m.id, m.path)]
models = collect_local_models(models_root)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The collect_local_models function performs heavy synchronous filesystem operations. Calling it directly within an async def route blocks the FastAPI event loop, stalling all other concurrent requests. Running it in a thread pool using asyncio.to_thread keeps the event loop responsive.

Suggested change
models = collect_local_models(models_root)
models = await asyncio.to_thread(collect_local_models, models_root)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fd0b70d488

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

"object": "model",
"created": _created,
"owned_by": "local",
"loaded": False,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep /v1/models limited to servable models

When the catalog includes entries marked loaded: false, OpenAI-compatible clients can select one of those advertised ids and then call /v1/chat/completions, but the chat route does not load or route by payload.model: it uses the currently loaded GGUF/non-GGUF model instead (routes/inference.py around 4518-4534), or errors if none is loaded. In a server with model A loaded and model B merely present on disk, /v1/models now advertises B even though requests for B will either run A silently or fail, which can corrupt experiment results for clients that trust the model list.

Useful? React with 👍 / 👎.

"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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return the public id from wrapped chat responses

For a loaded GGUF on the normal Studio-wrapped path (for example plain chat without tools or response_format), /v1/models now advertises the sanitized id here, but openai_chat_completions still sets model_name = llama_backend.model_identifier and uses that raw value in its ChatCompletion and stream chunks (routes/inference.py around 4991, 5175, and 5956). A client that discovers Qwen3-Q4 can therefore receive /srv/models/Qwen3-Q4.gguf in the response model field, reintroducing the filesystem-path leak and making the advertised id inconsistent; the new --alias only affects llama-server passthrough responses.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the studio-model-id-sanitizer branch from 6cc8774 to 1e526a4 Compare June 20, 2026 14:37
@danielhanchen
danielhanchen force-pushed the studio-v1-models-catalog branch from fd0b70d to 027bb9c Compare June 20, 2026 14:41

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f2dcf57d97

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Outdated
"""Locally available models (models dir + HF caches + LM Studio + scan
folders), cached for a few seconds. Returns a list of LocalModelInfo."""
now = time.monotonic()
if not _CATALOG_CACHE["models"] or (now - _CATALOG_CACHE["at"]) > _CATALOG_TTL_S:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor the catalog TTL for empty scans

When collect_local_models() returns [] (for example, a server with only a loaded model and no downloaded catalog entries, or a failed scan), this condition remains true because the cached list is falsy, so _CATALOG_CACHE["at"] is updated but never honored. Clients that poll /v1/models in that state will rescan the models dir, HF caches, LM Studio dirs, and custom folders on every request instead of once per 30 seconds, which can add avoidable latency and disk churn on large or slow model directories; track cache initialization separately or base the decision on at so empty results are cached too.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the studio-v1-models-catalog branch from f2dcf57 to 34ea2b6 Compare June 22, 2026 05:11
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

1 similar comment
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

danielhanchen and others added 3 commits June 22, 2026 05:26
…cal .gguf path

GET /v1/models reported the loaded model's internal identifier verbatim, which
for a direct local load is the absolute .gguf path. That leaks the host
filesystem layout and is awkward for clients to round-trip as a model id.

Add core.inference.model_ids.public_model_id: a local GGUF path collapses to its
clean file stem (Qwen3-30B-A3B-Q4_K_M), while Hugging Face repo ids (org/model)
and already-clean names pass through unchanged. Use it for the id in
_openai_model_objects (both backends), have GET /v1/models/{id} still accept a
legacy raw identifier for backward compatibility while returning the clean
object, and pass --alias to llama-server so its own /v1/models and the model
field of its proxied responses are clean as well.

Sanitize every other surface that echoed the identifier back to the client, so
the path cannot leak through a different endpoint: the non-GGUF chat completion
reply, GGUF and non-GGUF audio replies, /v1/messages (Anthropic-compatible), and
all status/echo envelopes streamed from /v1/responses. A raw .gguf path sent by
a client as the request model is likewise collapsed before it is echoed.

Deny a user-supplied --alias/-a in llama-server passthrough args: Studio appends
its sanitized alias and llama.cpp's last-wins parsing would otherwise let a
caller reintroduce the path leak.

Treat relative and home paths (./model, ../model, ~/model and their Windows
forms) as local paths in public_model_id so they are sanitized rather than
returned verbatim.
…aded model

The OpenAI-compatible /v1/models returned only the model currently resident in
memory, so a client could not discover what the server can actually serve.

Extract the model-picker scan logic into a shared routes.models.collect_local_models
so the UI and the API enumerate from one source and cannot drift. /v1/models now
merges the loaded model(s) with locally available (downloaded/cached) models from
the models dir, HF caches, LM Studio dirs, and user scan folders, deduplicated by
clean public id, with a short scan cache. Each entry carries a 'loaded' flag;
loaded entries keep their context fields. /v1/models/{id} resolves any known model
(loaded or available) and still accepts a legacy raw identifier.

The catalog scan walks many directories and stats many files, so it runs in a
worker thread via asyncio.to_thread instead of inline: calling it directly in the
async handler blocked the event loop and stalled concurrent requests and in-flight
inference streams. A double-checked asyncio.Lock collapses a burst of simultaneous
/v1/models calls into a single scan. /v1/models/{id} uses model_id_matches for the
legacy-identifier fallback so the clean-id and raw-path forms are matched
consistently.
@danielhanchen
danielhanchen force-pushed the studio-model-id-sanitizer branch from 1e526a4 to 18dcdf9 Compare June 22, 2026 05:27
@danielhanchen
danielhanchen force-pushed the studio-v1-models-catalog branch from 8c27e72 to 6a835a6 Compare June 22, 2026 05:27
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6a835a6211

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Outdated
lock with a double-check collapses a burst of simultaneous /v1/models calls
into a single scan instead of one per request."""
now = time.monotonic()
if _CATALOG_CACHE["models"] and (now - _CATALOG_CACHE["at"]) <= _CATALOG_TTL_S:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cache empty catalog results

When the local scan returns an empty list (fresh installs with no downloaded models, or after the exception path assigns []), this truthiness check treats the just-refreshed cache as invalid, and the identical check under the lock does the same. That makes every /v1/models request take the lock and rescan the models/HF/custom folders despite _CATALOG_CACHE["at"] being updated, defeating the TTL in a common empty-catalog case; base cache validity on the timestamp or use a separate initialized sentinel instead.

Useful? React with 👍 / 👎.

Comment on lines +6044 to +6049
obj = {
"id": cid,
"object": "model",
"created": _created,
"owned_by": "local",
"loaded": False,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid advertising unloaded models as callable

With a standard OpenAI client, every model returned by /v1/models is a candidate for /v1/chat/completions, but this branch now inserts locally cached entries with loaded: False. I checked openai_chat_completions, and the local backend path still ignores payload.model and serves whichever GGUF/Unsloth model is already loaded (studio/backend/routes/inference.py:4612-4667), so selecting one of these newly listed unloaded ids silently runs a different model instead of failing or loading that id.

Useful? React with 👍 / 👎.


# Locally available (downloaded/cached) models that are not already loaded.
for info in await _cached_local_catalog():
cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve distinct local models with the same public id

When the scan returns two different local paths with the same basename (for example two custom folders each containing model.gguf), this derives the same cid for both via public_model_id(...), and the following cid in by_id skip drops the later entry. /api/models/local keeps those paths distinct, so /v1/models is no longer the full local catalog in that duplicate-filename/custom-folder case; use a collision-resistant path-free id instead of deduping solely by basename.

Useful? React with 👍 / 👎.

Match the preview routes (/p/.../v1/models), which already report
owned_by="unsloth-studio", so the catalog and per-checkpoint surfaces are
consistent for OpenAI-compatible clients. Covers the loaded GGUF/Unsloth
entries and the locally-available catalog entries.
Base automatically changed from studio-model-id-sanitizer to main June 26, 2026 19:07
# Conflicts:
#	studio/backend/core/inference/model_ids.py
#	studio/backend/routes/inference.py
#	studio/backend/tests/test_model_ids.py

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2175a2dead

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 47859b6990

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 59316bd51f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved
@oobabooga

Copy link
Copy Markdown
Member

Verified live on a 2-GPU box (Qwen3-0.6B GGUF). /v1/models lists the full local catalog with clean ids and no path leaks. Loaded vs available is flagged correctly, and the active model is deduped to one entry. /v1/models/{id} resolves known, slashed, and legacy ids, and 404s on unknown ones. The cache holds under a concurrent burst. Unit suites green, and full CI passes on my fork PR: oobabooga#10

Follow-ups on top of the review: cache empty and errored scans for the TTL, stamp the TTL after the scan, skip the scan on loaded-id retrieval, plus minor cleanup. Also reverted the path-based alias dedup. It suppressed a cosmetic duplicate but silently hid distinct models sharing a basename, and the common HF-GGUF path dedups fine without it.

@oobabooga
oobabooga merged commit b11966b into main Jun 26, 2026
47 checks passed
@oobabooga
oobabooga deleted the studio-v1-models-catalog branch June 26, 2026 23:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants