The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(router): route batch creates to mode batch deployments and expose supported_endpoints on /model_group/info (#47376)
Mateo Wang8a2782e41ce5
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 295f4380d7d..c17e0c67d68 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -17757,7 +17757,7 @@ async def model_deprecations(def get_model_group_info(- llm_router: Router, all_models_str: Sequence[str], model_group: str | None+ llm_router: Router, all_models_str: Sequence[str], model_group: str | None, team_id: str | None = None) -> list[ModelGroupInfoProxy]:model_groups: Final[list[ModelGroupInfoProxy]] = []@@ -17770,7 +17770,7 @@ def get_model_group_info(if model_group is not None and model_group != model:continue- _model_group_info = llm_router.get_model_group_info(model_group=model)+ _model_group_info = llm_router.get_model_group_info(model_group=model, team_id=team_id)if _model_group_info is not None:model_groups.append(ModelGroupInfoProxy.model_validate(_model_group_info.model_dump()))@@ -18002,7 +18002,10 @@ async def model_group_info(model_groups: Final = await append_agents_to_model_group(model_groups=get_model_group_info(- llm_router=llm_router, all_models_str=listed_group_names, model_group=model_group+ llm_router=llm_router,+ all_models_str=listed_group_names,+ model_group=model_group,+ team_id=user_api_key_dict.team_id,),user_api_key_dict=user_api_key_dict,)diff --git a/litellm/router.py b/litellm/router.pyindex 1ecff167126..54d4cce4656 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -190,10 +190,13 @@ from litellm.router_utils.auto_router_model_naming import (count_capability_routers,)from litellm.router_utils.batch_utils import (+ batch_create_routing,+ deployment_supported_endpoints,get_router_metadata_variable_name,is_batch_retrieve_call_type,replace_model_in_jsonl,should_replace_model_in_jsonl,+ without_deployments_that_cannot_batch,)from litellm.router_utils.client_initalization_utils import InitalizeCachedClient, MaxParallelRequestsLimitfrom litellm.router_utils.clientside_credential_handler import (@@ -202,6 +205,7 @@ from litellm.router_utils.clientside_credential_handler import ()from litellm.router_utils.common_utils import (MID_STREAM_CONTINUATION_KWARG,+ deployments_the_caller_may_use,filter_team_based_models,filter_web_search_deployments,format_fallback_outcome_message,@@ -7184,12 +7188,13 @@ class Router:try:verbose_router_logger.debug("Inside _acreate_batch()- model: %s; kwargs: %s", model, kwargs)parent_otel_span: Final = get_parent_otel_span_from_kwargs(kwargs)- deployment: Final = await self.async_get_available_deployment(- model=model,- messages=[{"role": "user", "content": "files-api-fake-text"}],- specific_deployment=kwargs.pop("specific_deployment", None),- request_kwargs=kwargs,- )+ with batch_create_routing():+ deployment: Final = await self.async_get_available_deployment(+ model=model,+ messages=[{"role": "user", "content": "files-api-fake-text"}],+ specific_deployment=kwargs.pop("specific_deployment", None),+ request_kwargs=kwargs,+ )data: Final = deployment["litellm_params"].copy()model_name: Final = data["model"]@@ -12056,7 +12061,9 @@ class Router:)return model_info- def _set_model_group_info(self, model_group: str, user_facing_model_group_name: str) -> ModelGroupInfo | None:+ def _set_model_group_info(+ self, model_group: str, user_facing_model_group_name: str, team_id: str | None = None+ ) -> ModelGroupInfo | None:"""For a given model group name, return the combined model info@@ -12187,6 +12194,7 @@ class Router:**model_info,"supports_fast_mode": True,"supported_reasoning_efforts": None,+ "supported_endpoints": None,})else:@@ -12264,6 +12272,23 @@ class Router:if model_info.get("rpm", None) is not None and _deployment_rpm is None:_deployment_rpm = model_info.get("rpm")+ model_group_info.supported_endpoints = (+ tuple(+ dict.fromkeys(+ (+ *(model_group_info.supported_endpoints or ()),+ *(+ deployment_supported_endpoints(+ model_info.get("supported_endpoints"), model, llm_provider+ )+ if team_may_use_deployment(_configured_model_info(model).get("team_id"), team_id)+ else ()+ ),+ )+ )+ )+ or None+ )model_group_info.supports_fast_mode = model_group_info.supports_fast_mode and (AnthropicModelInfo.supports_fast_mode(litellm_model, llm_provider))@@ -12322,7 +12347,9 @@ class Router:return model_group_info- def get_model_group_info(self, model_group: str, *, include_hidden: bool = False) -> ModelGroupInfo | None:+ def get_model_group_info(+ self, model_group: str, *, include_hidden: bool = False, team_id: str | None = None+ ) -> ModelGroupInfo | None:"""For a given model group name, return the combined model info@@ -12346,10 +12373,13 @@ class Router:return self._set_model_group_info(model_group=_router_model_group,user_facing_model_group_name=model_group,+ team_id=team_id,)## Check if actual model- return self._set_model_group_info(model_group=model_group, user_facing_model_group_name=model_group)+ return self._set_model_group_info(+ model_group=model_group, user_facing_model_group_name=model_group, team_id=team_id+ )async def get_model_group_usage(self, model_group: str) -> tuple[int | None, int | None]:"""@@ -14585,8 +14615,15 @@ class Router:## ORDER FILTERING ## -> if user set 'order' in deployments, return deployments with lowest order (e.g. order=1 > order=2)_target_order: Final = (request_kwargs or {}).pop("_target_order", None)+ batch_candidates: Final = cast( # cast-ok: router deployments are plain dicts+ list[dict[str, object]], healthy_deployments+ )healthy_deployments = litellm.utils.get_order_filtered_deployments(- list(self._narrow_to_video_deployment(cast(list[dict[str, object]], healthy_deployments))),+ list(+ self._narrow_to_video_deployment(+ without_deployments_that_cannot_batch(batch_candidates, caller_deployments=lambda: batch_candidates)+ )+ ),target_order=_target_order,)@@ -15788,8 +15825,19 @@ class Router:## ORDER FILTERING ## -> if user set 'order' in deployments, return deployments with lowest order (e.g. order=1 > order=2)_target_order: Final = (request_kwargs or {}).pop("_target_order", None)+ batch_candidates: Final = cast( # cast-ok: router deployments are plain dicts+ list[dict[str, object]], healthy_deployments+ )healthy_deployments = litellm.utils.get_order_filtered_deployments(- list(self._narrow_to_video_deployment(healthy_deployments)), target_order=_target_order+ list(+ self._narrow_to_video_deployment(+ without_deployments_that_cannot_batch(+ batch_candidates,+ caller_deployments=lambda: deployments_the_caller_may_use(batch_candidates, routing_kwargs),+ )+ )+ ),+ target_order=_target_order,)## WEIGHTED FAILOVER EXCLUSION ## -> drop deployments already tried indiff --git a/litellm/router_utils/batch_utils.py b/litellm/router_utils/batch_utils.pyindex d71696a66b1..88c58412e01 100644--- a/litellm/router_utils/batch_utils.py+++ b/litellm/router_utils/batch_utils.py@@ -1,16 +1,26 @@import ioimport json-from collections.abc import Iterable+from collections.abc import Callable, Generator, Iterable, Mapping, Sequence+from contextlib import contextmanager+from contextvars import ContextVarfrom os import PathLike-from typing import Final+from typing import Final, TypeVar-from pydantic import TypeAdapter+from pydantic import TypeAdapter, ValidationErrorfrom litellm._logging import verbose_loggerfrom litellm.types.llms.openai import FileTypes, OpenAIFilesPurpose-from litellm.types.utils import CallTypes+from litellm.types.utils import CallTypes, LlmProviders_DECODED_JSONL_ROW: Final = TypeAdapter(object)+_DEPLOYMENT_FIELD: Final = TypeAdapter(Mapping[str, object])+_ENDPOINT_PATHS: Final = TypeAdapter(tuple[str, ...])++BATCH_ENDPOINT: Final = "/v1/batch"+_AZURE_PROVIDERS: Final = frozenset({LlmProviders.AZURE.value, LlmProviders.AZURE_AI.value})++_batch_create_routing: Final[ContextVar[bool]] = ContextVar("batch_create_routing", default=False)+_DeploymentT: Final = TypeVar("_DeploymentT", bound=Mapping[str, object])class InMemoryFile(io.BytesIO):@@ -65,6 +75,72 @@ def parse_jsonl_with_embedded_newlines(content: str) -> list[dict]:return json_objects+@contextmanager+def batch_create_routing() -> Generator[None, None, None]:+ token: Final = _batch_create_routing.set(True)+ try:+ yield+ finally:+ _batch_create_routing.reset(token)+++def is_batch_create_routing() -> bool:+ return _batch_create_routing.get()+++def _deployment_field(deployment: Mapping[str, object], field: str) -> Mapping[str, object]:+ return _DEPLOYMENT_FIELD.validate_python(deployment.get(field) or {})+++def is_batch_capable(deployment: Mapping[str, object]) -> bool:+ return _deployment_field(deployment, "model_info").get("mode") == "batch"+++def _deployment_provider(deployment: Mapping[str, object]) -> str | None:+ litellm_params: Final = _deployment_field(deployment, "litellm_params")+ configured_provider: Final = litellm_params.get("custom_llm_provider")+ if isinstance(configured_provider, str):+ return configured_provider+ model: Final = litellm_params.get("model")+ return model.split("/", 1)[0] if isinstance(model, str) and "/" in model else None+++def _cannot_run_batches(deployment: Mapping[str, object], provider: str | None) -> bool:+ return provider in _AZURE_PROVIDERS and not is_batch_capable(deployment)+++def without_deployments_that_cannot_batch(+ deployments: Sequence[_DeploymentT], caller_deployments: Callable[[], Iterable[Mapping[str, object]]]+) -> Sequence[_DeploymentT]:+ if not is_batch_create_routing() or not any(is_batch_capable(deployment) for deployment in caller_deployments()):+ return deployments+ return [+ deployment+ for deployment in deployments+ if not _cannot_run_batches(deployment, _deployment_provider(deployment))+ ]+++def _endpoint_paths(configured: object) -> tuple[str, ...]:+ try:+ return _ENDPOINT_PATHS.validate_python(configured)+ except ValidationError:+ return ()+++def deployment_supported_endpoints(+ resolved_endpoints: object, deployment: Mapping[str, object], provider: str | None+) -> tuple[str, ...]:+ endpoints: Final = _endpoint_paths(resolved_endpoints)+ if is_batch_capable(deployment) and provider in _AZURE_PROVIDERS:+ return (BATCH_ENDPOINT,)+ if is_batch_capable(deployment):+ return endpoints if BATCH_ENDPOINT in endpoints else (*endpoints, BATCH_ENDPOINT)+ if _cannot_run_batches(deployment, provider):+ return tuple(endpoint for endpoint in endpoints if endpoint != BATCH_ENDPOINT)+ return endpoints++def should_replace_model_in_jsonl(purpose: OpenAIFilesPurpose,passthrough: bool = False,diff --git a/litellm/router_utils/common_utils.py b/litellm/router_utils/common_utils.pyindex caab6e572de..a00d84babf3 100644--- a/litellm/router_utils/common_utils.py+++ b/litellm/router_utils/common_utils.py@@ -35,6 +35,9 @@ _V = TypeVar("_V")MID_STREAM_CONTINUATION_KWARG: Final = "_mid_stream_continuation"ROUTER_ONLY_CALL_KWARGS: Final = frozenset({"silent_model", "include_fallback_errors", MID_STREAM_CONTINUATION_KWARG})_OBJECT_MAPPING_ADAPTER: Final[TypeAdapter[Mapping[object, object]]] = TypeAdapter(Mapping[object, object])+_DEPLOYMENT_ROWS_ADAPTER: Final[TypeAdapter[tuple[Mapping[str, object], ...]]] = TypeAdapter(+ tuple[Mapping[str, object], ...]+)def with_admin_api_key_secret_reference(deployment: Deployment) -> Deployment:@@ -327,6 +330,20 @@ def filter_team_based_models(]+def deployments_the_caller_may_use(+ deployments: Sequence[Mapping[str, object]], request_kwargs: Mapping[str, object] | None+) -> tuple[Mapping[str, object], ...]:+ try:+ return _DEPLOYMENT_ROWS_ADAPTER.validate_python(+ filter_team_based_models(+ [dict(deployment) for deployment in deployments],+ None if request_kwargs is None else dict(request_kwargs),+ )+ )+ except BadRequestError:+ return ()++_WEB_SEARCH_TOOL_TYPES: Final = frozenset({"web_search", "web_search_preview"})diff --git a/litellm/types/router.py b/litellm/types/router.pyindex 36d298b2bc2..47dafcf275d 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -982,6 +982,7 @@ class ModelGroupInfo(LiteLLMBaseModel):supported_openai_params: list[str] | None = Field(default=[])configurable_clientside_auth_params: CONFIGURABLE_CLIENTSIDE_AUTH_PARAMS = Nonedescription: str | None = None+ supported_endpoints: tuple[str, ...] | None = Nonedef __init__(self, **data) -> None:for field_name, field_type in _resolved_annotations(self.__class__).items():diff --git a/tests/code_coverage_tests/router_code_coverage.py b/tests/code_coverage_tests/router_code_coverage.pyindex e72a85b7056..3f0ad07a876 100644--- a/tests/code_coverage_tests/router_code_coverage.py+++ b/tests/code_coverage_tests/router_code_coverage.py@@ -141,6 +141,16 @@ ignored_function_names = ["async_admit_deployment_turn", # Bound as the WebSocket turn_admission partial, tested through it in test_router_helper_utils.py"_deployment_as_configured_now", # Read by async_admit_deployment_turn, tested through turn_admission in test_router_helper_utils.py"_admit_turn_through_routing_strategy", # Run by async_admit_deployment_turn, tested through turn_admission in test_router_helper_utils.py+ "without_deployments_that_cannot_batch", # Tested through the Azure and OpenAI mixed-group acreate_batch tests in test_router.py+ "batch_create_routing", # Tested through the mixed-group acreate_batch tests in test_router.py+ "is_batch_create_routing", # Tested through the chat-after-batch-create test in test_router.py+ "is_batch_capable", # Tested through the mixed-group acreate_batch and model group info tests in test_router.py+ "deployments_the_caller_may_use", # Tested through the usage-based-routing team batch create test in test_router.py+ "deployment_supported_endpoints", # Tested through the model group info batch endpoint tests in test_router.py+ "_endpoint_paths", # Read by deployment_supported_endpoints, tested through the malformed endpoint list group info test in test_router.py+ "_deployment_field", # Read by is_batch_capable, tested through the mixed-group tests in test_router.py+ "_deployment_provider", # Read by without_deployments_that_cannot_batch, tested through the mixed-group tests in test_router.py+ "_cannot_run_batches", # Tested through the Azure and OpenAI mixed-group acreate_batch tests in test_router.py]diff --git a/tests/unit/proxy/proxy_server/test_routes_model_info.py b/tests/unit/proxy/proxy_server/test_routes_model_info.pyindex cb7b5b13fa3..2c0e0944edb 100644--- a/tests/unit/proxy/proxy_server/test_routes_model_info.py+++ b/tests/unit/proxy/proxy_server/test_routes_model_info.py@@ -801,7 +801,7 @@ def model_group_info_router(monkeypatch):router.get_model_access_groups.return_value = {}router.get_model_list.return_value = []- def model_group_info(*, llm_router, all_models_str, model_group):+ def model_group_info(*, llm_router, all_models_str, model_group, team_id=None):return [ModelGroupInfoProxy(model_group=name, providers=[]) for name in all_models_str]async def append_agents_to_model_group(*, model_groups, user_api_key_dict):@@ -866,6 +866,53 @@ def test_model_group_info_internal_user_key_model_restriction_applies(client, auassert [model["model_group"] for model in response.json()["data"]] == ["gpt-4"]+def _azure_group_deployment(sku_host: str, mode: str, **model_info: object) -> dict[str, object]:+ return {+ "model_name": "gpt-mixed",+ "litellm_params": {+ "model": f"azure/{sku_host}",+ "api_base": f"https://{sku_host}.openai.azure.com",+ "api_key": "dummy-key",+ "api_version": "2025-04-01-preview",+ },+ "model_info": {"mode": mode, **model_info},+ }++[email protected](("team_id", "lists_batch"), [(None, False), ("team-a", True)])+def test_model_group_info_lists_batch_only_to_the_team_that_owns_the_batch_deployment(+ client, auth_as, monkeypatch, team_id: str | None, lists_batch: bool+):+ from litellm.proxy._types import LitellmUserRoles+ from litellm.proxy.agent_endpoints import model_list_helpers++ router: Final = litellm.Router(+ model_list=[+ _azure_group_deployment("chat-sku", "chat", supported_endpoints=["/v1/chat/completions"]),+ _azure_group_deployment("batch-sku", "batch", team_id="team-a"),+ ]+ )++ async def append_agents_to_model_group(*, model_groups, user_api_key_dict):+ return model_groups++ monkeypatch.setattr(proxy_server, "llm_router", router)+ monkeypatch.setattr(proxy_server, "llm_model_list", router.model_list)+ monkeypatch.setattr(proxy_server, "user_model", None)+ monkeypatch.setattr(proxy_server, "general_settings", {})+ monkeypatch.setattr(proxy_server, "prisma_client", None)+ monkeypatch.setattr(+ model_list_helpers, "append_agents_to_model_group", AsyncMock(side_effect=append_agents_to_model_group)+ )++ with auth_as(LitellmUserRoles.PROXY_ADMIN, team_id=team_id):+ response: Final = client.get("/model_group/info")++ assert response.status_code == 200+ groups: Final = {group["model_group"]: group for group in response.json()["data"]}+ assert ("/v1/batch" in (groups["gpt-mixed"]["supported_endpoints"] or ())) is lists_batch++# ---------------------------------------------------------------------------# GET /v2/model/info?exclude_auto_routers# ---------------------------------------------------------------------------diff --git a/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.py b/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.pyindex 4267cdbbcc9..07886745222 100644--- a/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.py+++ b/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.py@@ -25,7 +25,7 @@ class _FakeRouter:infos: Mapping[str, ModelGroupInfo]- def get_model_group_info(self, model_group: str) -> ModelGroupInfo | None:+ def get_model_group_info(self, model_group: str, team_id: str | None = None) -> ModelGroupInfo | None:return self.infos.get(model_group)@@ -325,7 +325,7 @@ def test_no_router_answers_with_a_problem_rather_than_the_openai_error_shape(mondef test_an_unexpected_router_failure_answers_as_a_problem_not_the_openai_error_shape(monkeypatch):class _Exploding:- def get_model_group_info(self, model_group: str) -> ModelGroupInfo:+ def get_model_group_info(self, model_group: str, team_id: str | None = None) -> ModelGroupInfo:raise RuntimeError("router blew up")monkeypatch.setattr(litellm, "public_model_groups", ["boom"])diff --git a/tests/unit/test_router/test_router.py b/tests/unit/test_router/test_router.pyindex 9b1bdbf702e..90674dcb3f9 100644--- a/tests/unit/test_router/test_router.py+++ b/tests/unit/test_router/test_router.py@@ -2375,6 +2375,140 @@ def test_model_group_info_description_from_model_info():assert result.description == "State-of-the-art language model."[email protected]("chat_deployment_first", [True, False])+def test_model_group_info_lists_batch_for_a_mixed_chat_and_batch_group(chat_deployment_first: bool):+ chat: Final = _azure_sku_deployment(+ "gpt-mixed", "unmapped-chat-sku", "chat", supported_endpoints=["/v1/chat/completions"]+ )+ batch: Final = _azure_sku_deployment("gpt-mixed", "unmapped-batch-sku", "batch")+ router: Final = Router(model_list=[chat, batch] if chat_deployment_first else [batch, chat])++ info: Final = router.get_model_group_info("gpt-mixed")++ assert info is not None+ assert sorted(info.supported_endpoints or ()) == ["/v1/batch", "/v1/chat/completions"]+++def test_model_group_info_lists_no_batch_for_a_chat_only_group():+ router: Final = Router(+ model_list=[+ _azure_sku_deployment(+ "gpt-declared", "unmapped-chat-sku", "chat", supported_endpoints=["/v1/chat/completions"]+ ),+ _azure_sku_deployment("gpt-undeclared", "unmapped-undeclared-sku", "chat"),+ ]+ )++ declared: Final = router.get_model_group_info("gpt-declared")+ undeclared: Final = router.get_model_group_info("gpt-undeclared")++ assert declared is not None and declared.supported_endpoints == ("/v1/chat/completions",)+ assert undeclared is not None and undeclared.supported_endpoints is None++[email protected](("provider", "lists_batch"), [("azure", False), ("azure_ai", False), ("openai", True)])+def test_model_group_info_lists_cost_map_batch_only_for_providers_that_batch_on_any_deployment(+ provider: str, lists_batch: bool+):+ """Azure runs batches only on a separate batch deployment, though the cost map lists /v1/batch for its chat+ models, so an Azure chat group must not advertise it. OpenAI batches through the deployment that serves chat,+ so its cost map listing stands."""+ cost_map_name, cost_map_endpoints = next(+ (name, tuple(info["supported_endpoints"]))+ for name, info in litellm.model_cost.items()+ if info.get("litellm_provider") == provider+ and info.get("mode") == "chat"+ and "/v1/batch" in (info.get("supported_endpoints") or ())+ )+ router: Final = Router(+ model_list=[+ {+ "model_name": "gpt-chat",+ "litellm_params": {"model": f"{provider}/{cost_map_name.removeprefix(f'{provider}/')}"},+ }+ ]+ )++ info: Final = router.get_model_group_info("gpt-chat")++ assert info is not None+ assert info.supported_endpoints == tuple(+ endpoint for endpoint in cost_map_endpoints if lists_batch or endpoint != "/v1/batch"+ )+++ "malformed_endpoints",+ ["/v1/chat/completions", [{"path": "/v1/chat/completions"}], [1], {"/v1/batch": True}],+)+def test_model_group_info_skips_a_malformed_endpoint_list_instead_of_failing(malformed_endpoints: object):+ router: Final = Router(+ model_list=[+ _azure_sku_deployment("gpt-mixed", "chat-sku", "chat", supported_endpoints=["/v1/chat/completions"]),+ _azure_sku_deployment("gpt-mixed", "odd-sku", "chat", supported_endpoints=malformed_endpoints),+ ]+ )++ info: Final = router.get_model_group_info("gpt-mixed")++ assert info is not None and info.supported_endpoints == ("/v1/chat/completions",)+++def test_model_group_info_ignores_a_stored_batch_endpoint_on_an_azure_chat_deployment():+ """Admin UI saves before v1.104.0 stored the cost map's endpoint list, /v1/batch included, on Azure chat rows,+ so a stored list cannot mark a deployment as one that runs batches."""+ router: Final = Router(+ model_list=[+ _azure_sku_deployment(+ "gpt-stored-endpoints",+ "unmapped-chat-sku",+ "chat",+ supported_endpoints=["/v1/chat/completions", "/v1/batch"],+ )+ ]+ )++ info: Final = router.get_model_group_info("gpt-stored-endpoints")++ assert info is not None and info.supported_endpoints == ("/v1/chat/completions",)++[email protected](("team_id", "lists_batch"), [(None, False), ("team-b", False), ("team-a", True)])+def test_model_group_info_lists_batch_only_to_callers_that_may_use_the_batch_deployment(+ team_id: str | None, lists_batch: bool+):+ router: Final = Router(+ model_list=[+ _azure_sku_deployment("gpt-mixed", "chat-sku", "chat", supported_endpoints=["/v1/chat/completions"]),+ _azure_sku_deployment("gpt-mixed", "batch-sku", "batch", team_id="team-a"),+ ]+ )++ info: Final = router.get_model_group_info("gpt-mixed", team_id=team_id)++ assert info is not None+ assert ("/v1/batch" in (info.supported_endpoints or ())) is lists_batch+++def test_model_group_info_lists_only_batch_for_an_azure_batch_deployment():+ """An Azure batch deployment answers chat, Responses, and Messages calls with 400 "The current operation is not+ allowed in this deployment", so a group of them must advertise only /v1/batch whatever the endpoint list says."""+ router: Final = Router(+ model_list=[+ _azure_sku_deployment(+ "gpt-batch-only",+ "batch-sku",+ "batch",+ supported_endpoints=["/v1/chat/completions", "/v1/responses", "/v1/batch"],+ )+ ]+ )++ info: Final = router.get_model_group_info("gpt-batch-only")++ assert info is not None and info.supported_endpoints == ("/v1/batch",)++def _alias_cost_router() -> Router:return Router(model_list=[@@ -12914,6 +13048,389 @@ async def test_acreate_batch_still_falls_back_within_the_owning_model_group():assert attempted_models == ["openai/gpt-4o-mini", "openai/gpt-4o-mini-backup"]+def _azure_sku_deployment(model_group: str, sku_host: str, mode: str, **model_info: object) -> dict[str, object]:+ return {+ "model_name": model_group,+ "litellm_params": {+ "model": f"azure/{sku_host}",+ "api_base": f"https://{sku_host}.openai.azure.com",+ "api_key": "dummy-key",+ "api_version": "2025-04-01-preview",+ },+ "model_info": {"mode": mode, **model_info},+ }+++_AZURE_BATCH_CREATED: Final = {+ "id": "batch_created",+ "object": "batch",+ "endpoint": "/v1/chat/completions",+ "input_file_id": "file-batch-input",+ "completion_window": "24h",+ "status": "validating",+ "created_at": 0,+}+++async def _create_batches(router: Router, model_group: str, attempts: int) -> None:+ for _ in range(attempts):+ await router.acreate_batch(+ model=model_group,+ input_file_id="file-batch-input",+ endpoint="/v1/chat/completions",+ completion_window="24h",+ )+++def _azure_chat_row_with_provider_param() -> dict[str, object]:+ row: Final = _azure_sku_deployment("gpt-mixed", "chat-sku", "chat")+ return {**row, "litellm_params": {**row["litellm_params"], "model": "chat-sku", "custom_llm_provider": "azure"}}+++_AZURE_CHAT_ROWS: Final = {+ "no-stored-list": lambda: _azure_sku_deployment("gpt-mixed", "chat-sku", "chat"),+ "stored-cost-map-list": lambda: _azure_sku_deployment(+ "gpt-mixed", "chat-sku", "chat", supported_endpoints=["/v1/chat/completions", "/v1/batch"]+ ),+ "custom-llm-provider-param": _azure_chat_row_with_provider_param,+}++[email protected]("build_chat_row", _AZURE_CHAT_ROWS.values(), ids=_AZURE_CHAT_ROWS.keys())[email protected]("routing_strategy", ["simple-shuffle", "latency-based-routing", "usage-based-routing"])+async def test_acreate_batch_on_a_mixed_group_only_reaches_batch_deployments(+ monkeypatch: pytest.MonkeyPatch, routing_strategy: str, build_chat_row: Callable[[], dict[str, object]]+):+ """Azure answers 400 invalid_deployment_type when a batch is created on a GlobalStandard+ (chat) deployment, so a group mixing chat and batch deployments must send every batch+ create to the deployment that /model_group/info names as the one listing /v1/batch."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[+ build_chat_row(),+ _azure_sku_deployment("gpt-mixed", "batch-sku", "batch"),+ ],+ routing_strategy=routing_strategy,+ num_retries=0,+ )++ with respx.mock(assert_all_called=False) as respx_mock:+ chat_route: Final = respx_mock.post(host="chat-sku.openai.azure.com").mock(+ return_value=httpx.Response(+ 400,+ json={"error": {"code": "invalid_deployment_type", "message": "SKU 'GlobalStandard' is not supported"}},+ )+ )+ batch_route: Final = respx_mock.post(host="batch-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ await _create_batches(router, "gpt-mixed", attempts=20)++ assert chat_route.call_count == 0+ assert batch_route.call_count == 20+++def _azure_wildcard_deployment(sku_host: str, mode: str) -> dict[str, object]:+ return {+ "model_name": "mixed-wild/*",+ "litellm_params": {+ "model": "azure/*",+ "api_base": f"https://{sku_host}.openai.azure.com",+ "api_key": "dummy-key",+ "api_version": "2025-04-01-preview",+ },+ "model_info": {"mode": mode},+ }+++async def test_acreate_batch_on_a_mixed_wildcard_group_only_reaches_batch_deployments(+ monkeypatch: pytest.MonkeyPatch,+):+ """A wildcard group resolves its deployments before the named-group path does, and its batch+ creates must still only reach the deployments declared with model_info.mode batch."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[_azure_wildcard_deployment("chat-sku", "chat"), _azure_wildcard_deployment("batch-sku", "batch")],+ num_retries=0,+ )++ with respx.mock(assert_all_called=False) as respx_mock:+ chat_route: Final = respx_mock.post(host="chat-sku.openai.azure.com").mock(+ return_value=httpx.Response(+ 400,+ json={"error": {"code": "invalid_deployment_type", "message": "SKU 'GlobalStandard' is not supported"}},+ )+ )+ batch_route: Final = respx_mock.post(host="batch-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ await _create_batches(router, "mixed-wild/gpt-5.4-mini", attempts=20)++ assert chat_route.call_count == 0+ assert batch_route.call_count == 20+++async def test_chat_calls_after_a_batch_create_still_use_every_deployment_in_the_group(+ monkeypatch: pytest.MonkeyPatch,+):+ """Only the batch create itself is narrowed to mode batch deployments. Chat calls the same task makes+ afterwards keep load balancing across the whole group."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[+ _azure_sku_deployment("gpt-mixed", "chat-sku", "chat", id="chat-deployment"),+ _azure_sku_deployment("gpt-mixed", "batch-sku", "batch", id="batch-deployment"),+ ],+ num_retries=0,+ )++ with respx.mock(assert_all_called=False) as respx_mock:+ respx_mock.post(host="batch-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ await _create_batches(router, "gpt-mixed", attempts=2)++ chat_deployments: Final = {+ (+ await router.acompletion(+ model="gpt-mixed", messages=[{"role": "user", "content": "hi"}], mock_response="ok"+ )+ )._hidden_params["model_id"]+ for _ in range(40)+ }++ assert chat_deployments == {"chat-deployment", "batch-deployment"}+++async def test_acreate_batch_on_a_group_without_batch_deployments_still_uses_every_deployment(+ monkeypatch: pytest.MonkeyPatch,+):+ """Bedrock and OpenAI batch through the same deployment that serves chat, so a group with+ no mode batch deployment keeps load balancing batch creates across all of them."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[+ _azure_sku_deployment("gpt-chat-only", "first-chat-sku", "chat"),+ _azure_sku_deployment("gpt-chat-only", "second-chat-sku", "chat"),+ ],+ num_retries=0,+ )++ with respx.mock(assert_all_called=False) as respx_mock:+ first_route: Final = respx_mock.post(host="first-chat-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ second_route: Final = respx_mock.post(host="second-chat-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ await _create_batches(router, "gpt-chat-only", attempts=40)++ assert first_route.call_count > 0+ assert second_route.call_count > 0+ assert first_route.call_count + second_route.call_count == 40++[email protected](("team_id", "reached_host"), [(None, "chat-sku"), ("team-a", "batch-sku")])+async def test_acreate_batch_prefers_only_the_batch_deployments_the_caller_may_use(+ monkeypatch: pytest.MonkeyPatch, team_id: str | None, reached_host: str+):+ """A batch deployment owned by one team must not take a mixed group's batch creates away from callers+ outside that team, who still reach the group's shared deployments."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[+ _azure_sku_deployment("gpt-mixed", "chat-sku", "chat"),+ _azure_sku_deployment("gpt-mixed", "batch-sku", "batch", team_id="team-a"),+ ],+ num_retries=0,+ )++ with respx.mock(assert_all_called=False) as respx_mock:+ routes: Final = {+ host: respx_mock.post(host=f"{host}.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ for host in ("chat-sku", "batch-sku")+ }+ await router.acreate_batch(+ model="gpt-mixed",+ input_file_id="file-batch-input",+ endpoint="/v1/chat/completions",+ completion_window="24h",+ metadata={"user_api_key_team_id": team_id},+ )++ assert {host: route.call_count for host, route in routes.items()} == {+ host: int(host == reached_host) for host in routes+ }+++async def test_acreate_batch_on_a_legacy_routing_strategy_keeps_shared_deployments_for_callers_outside_the_batch_team(+ monkeypatch: pytest.MonkeyPatch,+):+ """usage-based-routing picks through the sync path, which keeps every team's deployments, so a batch deployment+ owned by one team must not pull the creates of callers outside that team onto its credentials."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[+ _azure_sku_deployment("gpt-mixed", "chat-sku", "chat"),+ _azure_sku_deployment("gpt-mixed", "batch-sku", "batch", team_id="team-a"),+ ],+ routing_strategy="usage-based-routing",+ num_retries=0,+ )++ with respx.mock(assert_all_called=False) as respx_mock:+ chat_route: Final = respx_mock.post(host="chat-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ respx_mock.post(host="batch-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ for _ in range(30):+ await router.acreate_batch(+ model="gpt-mixed",+ input_file_id="file-batch-input",+ endpoint="/v1/chat/completions",+ completion_window="24h",+ metadata={"user_api_key_team_id": None},+ )++ assert chat_route.call_count > 0+++ ("build_deployment", "model_name"),+ [+ (functools.partial(_azure_sku_deployment, "gpt-mixed"), "gpt-mixed"),+ (_azure_wildcard_deployment, "mixed-wild/gpt-5.4-mini"),+ ],+ ids=["named-group", "wildcard-group"],+)+def test_credentials_for_a_mixed_group_name_keep_resolving_to_its_first_deployment(+ build_deployment: Callable[[str, str], dict[str, object]], model_name: str+):+ """Model-encoded file, batch, and vector store ids name only the group, and every read resolves their+ credentials by that name, so adding a batch deployment to a group must not move ids created earlier+ onto it."""+ router: Final = Router(model_list=[build_deployment("chat-sku", "chat"), build_deployment("batch-sku", "batch")])++ credentials: Final = router.get_deployment_credentials_with_provider(model_id=model_name)++ assert credentials is not None and credentials["api_base"] == "https://chat-sku.openai.azure.com"+++_AZURE_CHAT_SKU_REJECTS_BATCH: Final = httpx.Response(+ 400,+ json={"error": {"code": "invalid_deployment_type", "message": "The current deployment is not supported for batch jobs"}},+)+++async def test_acreate_batch_on_a_mixed_group_reaches_chat_as_on_main_while_its_batch_deployment_cools_down(+ monkeypatch: pytest.MonkeyPatch,+):+ """While the batch deployment cools down, a create goes where main sends it, so the caller keeps getting+ Azure's 400 instead of a router 429 that main never returned for this request."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[+ _azure_sku_deployment("gpt-mixed", "chat-sku", "chat"),+ _azure_sku_deployment("gpt-mixed", "batch-sku", "batch"),+ ],+ num_retries=0,+ )+ _cool_down(router, *(d["model_info"]["id"] for d in router.model_list if d["model_info"]["mode"] == "batch"))++ with respx.mock(assert_all_called=False) as respx_mock:+ chat_route: Final = respx_mock.post(host="chat-sku.openai.azure.com").mock(return_value=_AZURE_CHAT_SKU_REJECTS_BATCH)+ with pytest.raises(openai.BadRequestError):+ await _create_batches(router, "gpt-mixed", attempts=1)++ assert chat_route.call_count == 1+++async def test_acreate_batch_with_tags_that_match_only_the_chat_deployment_reaches_it_as_on_main(+ monkeypatch: pytest.MonkeyPatch,+):+ """Tag routing runs before the batch filter, so tags that leave only the chat deployment get Azure's 400 as+ on main instead of a router error saying no deployment matches the tags."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ chat: Final = _azure_sku_deployment("gpt-mixed", "chat-sku", "chat")+ batch: Final = _azure_sku_deployment("gpt-mixed", "batch-sku", "batch")+ router: Final = litellm.Router(+ model_list=[+ {**chat, "litellm_params": {**chat["litellm_params"], "tags": ["chat-pin"]}},+ {**batch, "litellm_params": {**batch["litellm_params"], "tags": ["batch-pin"]}},+ ],+ enable_tag_filtering=True,+ num_retries=0,+ )++ with respx.mock(assert_all_called=False) as respx_mock:+ chat_route: Final = respx_mock.post(host="chat-sku.openai.azure.com").mock(return_value=_AZURE_CHAT_SKU_REJECTS_BATCH)+ batch_route: Final = respx_mock.post(host="batch-sku.openai.azure.com").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ with pytest.raises(openai.BadRequestError):+ await router.acreate_batch(+ model="gpt-mixed",+ input_file_id="file-batch-input",+ endpoint="/v1/chat/completions",+ completion_window="24h",+ litellm_metadata={"tags": ["chat-pin"]},+ )+ await router.acreate_batch(+ model="gpt-mixed",+ input_file_id="file-batch-input",+ endpoint="/v1/chat/completions",+ completion_window="24h",+ litellm_metadata={"tags": ["batch-pin"]},+ )++ assert (chat_route.call_count, batch_route.call_count) == (1, 1)+++def _openai_deployment(model_group: str, host: str, mode: str, **model_info: object) -> dict[str, object]:+ return {+ "model_name": model_group,+ "litellm_params": {"model": "openai/gpt-5.4-mini", "api_base": f"https://{host}/v1", "api_key": "dummy-key"},+ "model_info": {"mode": mode, **model_info},+ }+++async def test_acreate_batch_on_an_openai_group_falls_back_to_chat_while_its_batch_deployment_cools_down(+ monkeypatch: pytest.MonkeyPatch,+):+ """OpenAI runs batches on the deployment that serves chat, so only Azure groups skip chat deployments for+ batch creates and an OpenAI group keeps serving them while its batch deployment cools down."""+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ router: Final = litellm.Router(+ model_list=[+ _openai_deployment("gpt-mixed", "chat.openai.test", "chat"),+ _openai_deployment("gpt-mixed", "batch.openai.test", "batch"),+ ],+ num_retries=0,+ )+ _cool_down(router, *(d["model_info"]["id"] for d in router.model_list if d["model_info"]["mode"] == "batch"))++ with respx.mock(assert_all_called=False) as respx_mock:+ chat_route: Final = respx_mock.post(host="chat.openai.test").mock(+ return_value=httpx.Response(200, json=_AZURE_BATCH_CREATED)+ )+ await _create_batches(router, "gpt-mixed", attempts=5)++ assert chat_route.call_count == 5++@pytest.mark.asyncioasync def test_acreate_batch_request_bedrock_tags_override_deployment_tags():import httpxdiff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 88d54d3731a..bf2fe4300a3 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -38261,6 +38261,8 @@ export interface components {providers: string[];/** Rpm */rpm?: number | null;+ /** Supported Endpoints */+ supported_endpoints?: string[] | null;/*** Supported Openai Params* @default []