Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
25170d0
feat(proxy): serve Anthropic-native /v1/models for Claude Code gatewa…
Ar-maan05 Jun 12, 2026
6898cff
refactor(proxy): move Anthropic model-list formatter into llms/anthro…
Ar-maan05 Jun 12, 2026
2ea0e34
fix(proxy): make model_list request param optional for direct callers
Ar-maan05 Jun 12, 2026
cdf8b57
style: apply ruff format to changed lines
Ar-maan05 Aug 1, 2026
57b6481
style: satisfy ruff strict-rule budget (UP006, I001)
Ar-maan05 Aug 1, 2026
78cf8e5
style: satisfy type-discipline budget (LIT002 mutable-ok, LIT009 pyri…
Ar-maan05 Aug 1, 2026
10798ca
Merge pull request #36286 from BerriAI/litellm_internal_staging
yuneng-berri Aug 8, 2026
6a919ae
Merge pull request #36304 from BerriAI/litellm_internal_staging
yuneng-berri Aug 8, 2026
2df3219
Merge branch 'main' into feat-anthropic-native-v1-models-2
Ar-maan05 Aug 9, 2026
814dd65
Merge remote-tracking branch 'origin/litellm_internal_staging' into f…
Ar-maan05 Aug 9, 2026
a1bad11
style: satisfy LIT001/LIT010 and drop explanatory comment per contrib…
Ar-maan05 Aug 9, 2026
7dd58b5
fix(proxy): translate team model names in the Anthropic /v1/models re…
Ar-maan05 Aug 9, 2026
492417f
ci: trigger buildkite status report
yassin-berriai Aug 14, 2026
d388590
feat(proxy): carry token limits into the Anthropic-native /v1/models …
Ar-maan05 Aug 14, 2026
8cc848f
Merge remote-tracking branch 'origin/litellm_internal_staging' into f…
Ar-maan05 Aug 14, 2026
9062c5c
Merge commit '492417f3ac' into feat-anthropic-native-v1-models-2
Ar-maan05 Aug 14, 2026
647034b
fix(proxy): cast the injected request so the anthropic-version guard …
Ar-maan05 Aug 14, 2026
b3248d7
fix(proxy): explain the model listing casts so the type-discipline ga…
Ar-maan05 Aug 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions litellm/llms/anthropic/common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
import copy
import re
from collections.abc import Mapping, Sequence
from datetime import datetime, timezone
from types import MappingProxyType
from typing import Any, Final, Literal

import httpx
from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError

import litellm
from litellm.constants import DEFAULT_MODEL_CREATED_AT_TIME
from litellm.litellm_core_utils.prompt_templates.common_utils import (
get_file_ids_from_messages,
)
Expand Down Expand Up @@ -1221,3 +1223,30 @@ def process_anthropic_headers(headers: httpx.Headers | dict) -> dict:

additional_headers: Final = {**llm_response_headers, **openai_headers}
return additional_headers


def create_anthropic_model_list_response(model_ids: Sequence[str]) -> Mapping[str, object]:
"""Build the Anthropic-native /v1/models envelope.

Clients that send an anthropic-version header parse the Anthropic Models API
shape (type/display_name/created_at plus has_more/first_id/last_id) and filter
the list themselves, so every model id is returned here
"""
created_at: Final = (
datetime.fromtimestamp(DEFAULT_MODEL_CREATED_AT_TIME, tz=timezone.utc).isoformat().replace("+00:00", "Z")
)
data: Final = [ # mutable-ok: JSON response body, serialized by the route and never mutated
{ # mutable-ok: JSON response body, serialized by the route and never mutated
"type": "model",
"id": model_id,
"display_name": model_id,
"created_at": created_at,
}
for model_id in model_ids
]
return { # mutable-ok: JSON response body, serialized by the route and never mutated
"data": data,
"has_more": False,
"first_id": model_ids[0] if model_ids else None,
"last_id": model_ids[-1] if model_ids else None,
}
16 changes: 16 additions & 0 deletions litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8988,6 +8988,7 @@ def _init_pyroscope(cls):
"/models", dependencies=[Depends(user_api_key_auth)], tags=["model management"]
) # if project requires model list
async def model_list(
request: Request = None, # pyright: ignore[reportArgumentType] # FastAPI always injects the Request; the None default only serves direct in-process callers
user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
return_wildcard_routes: bool | None = False,
team_id: str | None = None,
Expand Down Expand Up @@ -9024,6 +9025,9 @@ async def model_list(

settings: Final = cast(dict[str, object], general_settings) # any-ok: legacy settings

from litellm.llms.anthropic.common_utils import (
create_anthropic_model_list_response,
)
Comment on lines +9533 to +9535
from litellm.proxy.management_endpoints.common_utils import (
_user_has_admin_privileges,
)
Expand All @@ -9032,6 +9036,8 @@ async def model_list(
get_available_models_for_user,
)

wants_anthropic_format: Final = request is not None and request.headers.get("anthropic-version") is not None

# Validate scope parameter if provided
if scope is not None and scope != "expand":
raise HTTPException(
Expand Down Expand Up @@ -9099,6 +9105,11 @@ async def model_list(
if hidden_names:
all_models = [m for m in all_models if m not in hidden_names]

if wants_anthropic_format:
return create_anthropic_model_list_response(
TeamModelNameTranslator.translate_listing(all_models, llm_router, settings)
)

# Surface the public team name by default; legacy internal keys via flag.
# The internal routing key drives the metadata/fallback lookup, while the
# public name is what the client sees as the model id.
Expand Down Expand Up @@ -9139,6 +9150,11 @@ async def model_list(
if hidden_names:
all_models = [m for m in all_models if m not in hidden_names]

if wants_anthropic_format:
return create_anthropic_model_list_response(
TeamModelNameTranslator.translate_listing(all_models, llm_router, settings)
)

# Surface the public team name by default; legacy internal keys via flag.
# The internal routing key drives the metadata/fallback lookup, while the
# public name is what the client sees as the model id.
Expand Down
37 changes: 37 additions & 0 deletions tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2028,3 +2028,40 @@ def test_native_anthropic_probe_still_reads_anthropic_entry(
AnthropicModelInfo._is_adaptive_thinking_model("claude-opus-4-8", "anthropic")
is True
)
def test_create_anthropic_model_list_response_shape():
from litellm.llms.anthropic.common_utils import (
create_anthropic_model_list_response,
)

response = create_anthropic_model_list_response(
["claude-opus-4-6", "gpt-4o", "claude-haiku-4-5"]
)

assert "object" not in response
assert response["has_more"] is False
assert response["first_id"] == "claude-opus-4-6"
assert response["last_id"] == "claude-haiku-4-5"
assert [m["id"] for m in response["data"]] == [
"claude-opus-4-6",
"gpt-4o",
"claude-haiku-4-5",
]
for entry in response["data"]:
assert entry["type"] == "model"
assert entry["display_name"] == entry["id"]
# ISO 8601 with a Z suffix, as the Anthropic Models API returns.
assert entry["created_at"].endswith("Z")
assert "+00:00" not in entry["created_at"]


def test_create_anthropic_model_list_response_empty():
from litellm.llms.anthropic.common_utils import (
create_anthropic_model_list_response,
)

response = create_anthropic_model_list_response([])

assert response["data"] == []
assert response["has_more"] is False
assert response["first_id"] is None
assert response["last_id"] is None
69 changes: 69 additions & 0 deletions tests/test_litellm/proxy/proxy_server/test_routes_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,28 @@ def test_get_models_happy_path(client, auth_as, patched_models, path):
}


@pytest.mark.parametrize("path", ["/v1/models", "/models"])
def test_get_models_anthropic_format_when_header_present(
client, auth_as, patched_models, path
):
"""Pins: ``GET /v1/models`` returns the Anthropic-native models shape when
the caller sends an ``anthropic-version`` header (Claude Code gateway
discovery), while the default OpenAI shape is unchanged without it."""
with auth_as():
response = client.get(path, headers={"anthropic-version": "2023-06-01"})
assert response.status_code == 200
body = response.json()
assert "object" not in body
assert body["has_more"] is False
assert body["first_id"] == "gpt-4"
assert body["last_id"] == "claude-sonnet"
assert [m["id"] for m in body["data"]] == ["gpt-4", "claude-sonnet"]
for entry in body["data"]:
assert entry["type"] == "model"
assert entry["display_name"] == entry["id"]
assert entry["created_at"].endswith("Z")


@pytest.mark.parametrize("path", ["/v1/models", "/models"])
def test_get_models_invalid_scope_returns_400(client, auth_as, patched_models, path):
"""Pins: ``GET /v1/models``, ``GET /models`` (error path: invalid scope)."""
Expand Down Expand Up @@ -130,3 +152,50 @@ def test_get_model_by_id_not_found(client, auth_as, patched_models, path):
response = client.get(path)
assert response.status_code == 404
assert "not found" in response.text.lower()


@pytest.mark.parametrize("params", [{}, {"scope": "expand"}])
def test_anthropic_format_returns_public_team_model_name(
client, auth_as, patched_models, monkeypatch, params
):
"""Regression: the Anthropic-native listing must go through the same team
name translation as the OpenAI listing, so a caller never sees the internal
``model_name_{team_id}_{uuid}`` routing key."""
from litellm.proxy import utils as proxy_utils
from litellm.proxy.auth import model_checks

internal_name = "model_name_team-1_c0ffee"

patched_models.get_model_list = MagicMock(
return_value=[
{
"model_name": internal_name,
"model_info": {
"team_id": "team-1",
"team_public_model_name": "gpt-4-team",
},
}
]
)
patched_models.get_model_names = MagicMock(return_value=[internal_name])

async def _fake_get_available_models_for_user(**kwargs):
return [internal_name]

monkeypatch.setattr(
proxy_utils,
"get_available_models_for_user",
_fake_get_available_models_for_user,
)
monkeypatch.setattr(
model_checks, "get_complete_model_list", lambda **kwargs: [internal_name]
)

with auth_as():
response = client.get(
"/v1/models", params=params, headers={"anthropic-version": "2023-06-01"}
)

assert response.status_code == 200
assert [m["id"] for m in response.json()["data"]] == ["gpt-4-team"]
assert internal_name not in response.text
Loading