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
fix(proxy): route team key vector store calls to a team model of the store's provider (#46894)
mrinal-berria79dae764f0b
diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex 6f93bcd82dc..8bab7215b17 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -813,7 +813,23 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited prroute=ROUTE_ENDPOINT_MAPPING.get(route_type, route_type),param="model",)- team_model_name: Final = llm_router.map_team_model(data["model"], team_id) if team_id is not None else None+ custom_llm_provider: Final[object] = (+ JSON_OBJECT_ADAPTER.validate_python(data).get("custom_llm_provider")+ if route_type+ in (+ "avector_store_search",+ "avector_store_retrieve",+ "avector_store_update",+ "avector_store_delete",+ )+ else None+ )+ team_model_provider: Final[str | None] = custom_llm_provider if isinstance(custom_llm_provider, str) else None+ team_model_name: Final = (+ llm_router.map_team_model(data["model"], team_id, custom_llm_provider=team_model_provider)+ if team_id is not None+ else None+ )if team_model_name is not None:data["model"] = team_model_namereturn getattr(llm_router, f"{route_type}")(**data)diff --git a/litellm/router.py b/litellm/router.pyindex 1b3857dfb71..8d77fd0dac5 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -12565,26 +12565,56 @@ class Router:members: Final = routing_group.models if routing_group is not None else ()return served_model if served_model == target or served_model in members else model_name- def map_team_model(self, team_model_name: str | None, team_id: str) -> str | None:+ def map_team_model(+ self, team_model_name: str | None, team_id: str, custom_llm_provider: str | None = None+ ) -> str | None:"""- Check if team_model_name resolves to team-specific deployments.-- Returns the public model name (unchanged) so the router can find all- sibling deployments via team_id filtering, instead of collapsing to a- single internal model_name.+ Resolve explicit team models or select a deployment for model-less calls.- When team_model_name is None (e.g. vector store / file endpoints that- don't include a model in their request), returns the first matching- team deployment's team_public_model_name so the router can inject BYOK- credentials from the team-scoped deployment.-- Returns:- - str: the team_model_name if team deployments exist for this team- - None: if no team-specific model is found+ Model-less calls with no provider use the first team deployment. With a provider, they+ use the first team deployment of that provider, pinned by ID when its public name also+ covers another provider."""models: Final = self.get_model_list(model_name=team_model_name, team_id=team_id)if not models:return None+ if team_model_name is None and custom_llm_provider is not None:++ def team_deployment_public_name(deployment: DeploymentTypedDict) -> str | None:+ model_info: Final = _configured_model_info(deployment)+ if model_info.get("team_id") != team_id:+ return None+ team_public_model_name: Final = model_info.get("team_public_model_name")+ return (+ team_public_model_name+ if isinstance(team_public_model_name, str) and team_public_model_name+ else deployment["model_name"]+ )++ matching_deployment: Final = next(+ (+ model+ for model in models+ if team_deployment_public_name(model) is not None+ and provider_for_generic_call(model["litellm_params"]) == custom_llm_provider+ ),+ None,+ )+ if matching_deployment is None:+ return None+ public_name: Final = team_deployment_public_name(matching_deployment)+ if public_name is None:+ return None+ same_public_name_deployments: Final = tuple(+ candidate for candidate in models if team_deployment_public_name(candidate) == public_name+ )+ if all(+ provider_for_generic_call(candidate["litellm_params"]) == custom_llm_provider+ for candidate in same_public_name_deployments+ ):+ return public_name+ deployment_id: Final = _configured_model_info(matching_deployment).get("id")+ return deployment_id if isinstance(deployment_id, str) else Nonefor model in models:if model.get("model_info", {}).get("team_id") == team_id:if team_model_name is None:diff --git a/tests/integration/providers/test_vector_store_team_model_provider_wire.py b/tests/integration/providers/test_vector_store_team_model_provider_wire.pynew file mode 100644index 00000000000..5b986a64ff6--- /dev/null+++ b/tests/integration/providers/test_vector_store_team_model_provider_wire.py@@ -0,0 +1,192 @@+import json+import uuid+from collections.abc import Callable+from typing import Final++from integration._support.client import Gateway+from integration._support.wire import Reply, Request, wire_server+from pydantic import JsonValue, TypeAdapter++JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+QUERY: Final = "team provider vector search"+TEAM_ACCESS_KEY: Final = "AKIAINTEGRATIONTEAM01"+STORE_ACCESS_KEY: Final = "AKIASTOREKEY00000001"+_RETRIEVE_RESPONSE: Final = json.dumps(+ {+ "retrievalResults": [+ {+ "content": {"text": "matching Bedrock content"},+ "score": 0.87,+ "metadata": {+ "x-amz-bedrock-kb-source-uri": "s3://synthetic-bucket/vector-store.txt",+ "x-amz-bedrock-kb-chunk-id": "chunk-1",+ },+ }+ ]+ }+).encode()+_OPENAI_RESULT: Final[dict[str, JsonValue]] = {+ "file_id": "file-search-wire",+ "filename": "search.txt",+ "score": 0.91,+ "attributes": {"tenant": "a"},+ "content": [{"type": "text", "text": "matching OpenAI content"}],+}+_BEDROCK_RESULT: Final[dict[str, JsonValue]] = {+ "score": 0.87,+ "content": [{"text": "matching Bedrock content", "type": "text"}],+ "file_id": "s3://synthetic-bucket/vector-store.txt",+ "filename": "vector-store.txt",+ "attributes": {+ "x-amz-bedrock-kb-source-uri": "s3://synthetic-bucket/vector-store.txt",+ "x-amz-bedrock-kb-chunk-id": "chunk-1",+ },+}+++def _bedrock_retrieve_peer(knowledge_base_id: str, access_key: str) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ assert request.method == "POST"+ assert request.target == f"/knowledgebases/{knowledge_base_id}/retrieve", request.target+ assert request.headers["authorization"].startswith(f"AWS4-HMAC-SHA256 Credential={access_key}/")+ assert JSON_OBJECT.validate_json(request.body) == {+ "retrievalQuery": {"text": QUERY},+ "retrievalConfiguration": {"vectorSearchConfiguration": {"numberOfResults": 3}},+ }+ return Reply(body=_RETRIEVE_RESPONSE)++ return respond+++def _openai_search_peer(store_id: str) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ assert request.method == "POST"+ assert request.target == f"/v1/vector_stores/{store_id}/search", request.target+ assert request.headers["authorization"] == "Bearer team-openai-key"+ assert JSON_OBJECT.validate_json(request.body)["query"] == QUERY+ return Reply(+ body=json.dumps(+ {+ "object": "vector_store.search_results.page",+ "search_query": QUERY,+ "data": [_OPENAI_RESULT],+ "has_more": False,+ "next_page": None,+ }+ ).encode()+ )++ return respond+++def test_bedrock_vector_store_search_uses_bedrock_team_model_credentials(gateway: Gateway) -> None:+ knowledge_base_id: Final = f"KB{uuid.uuid4().hex[:8].upper()}"+ with wire_server(_bedrock_retrieve_peer(knowledge_base_id, TEAM_ACCESS_KEY)) as wire, gateway.scenario() as scenario:+ team: Final = scenario.team()+ scenario.model(+ model="langgraph/repro-agent",+ api_base="http://127.0.0.1:1",+ model_info={"team_id": team},+ )+ scenario.model(+ model="bedrock/us.anthropic.claude-sonnet-5-5",+ api_base=wire.url,+ aws_access_key_id=TEAM_ACCESS_KEY,+ aws_secret_access_key="synthetic-team-secret-key",+ aws_region_name="us-east-1",+ aws_bedrock_runtime_endpoint=wire.url,+ model_info={"team_id": team},+ )+ team_key: Final = scenario.key(team_id=team)+ gateway.post(+ "/vector_store/new",+ {+ "vector_store_id": knowledge_base_id,+ "custom_llm_provider": "bedrock",+ "litellm_params": {+ "aws_region_name": "us-east-1",+ "aws_bedrock_runtime_endpoint": wire.url,+ },+ },+ )+ scenario.cleanups.callback(gateway.post, "/vector_store/delete", {"vector_store_id": knowledge_base_id})++ response: Final = gateway.request(+ "POST",+ f"/v1/vector_stores/{knowledge_base_id}/search",+ {"query": QUERY, "max_num_results": 3},+ key=team_key,+ )+ assert response.status_code == 200, response.text+ assert JSON_OBJECT.validate_json(response.content)["data"] == [_BEDROCK_RESULT], response.text+ assert len(wire.drain()) == 1+++def test_bedrock_vector_store_search_uses_store_credentials_without_matching_team_model(+ gateway: Gateway,+) -> None:+ knowledge_base_id: Final = f"KB{uuid.uuid4().hex[:8].upper()}"+ with wire_server(_bedrock_retrieve_peer(knowledge_base_id, STORE_ACCESS_KEY)) as wire, gateway.scenario() as scenario:+ team: Final = scenario.team()+ scenario.model(+ model="langgraph/repro-agent",+ api_base="http://127.0.0.1:1",+ model_info={"team_id": team},+ )+ team_key: Final = scenario.key(team_id=team)+ gateway.post(+ "/vector_store/new",+ {+ "vector_store_id": knowledge_base_id,+ "custom_llm_provider": "bedrock",+ "litellm_params": {+ "aws_access_key_id": STORE_ACCESS_KEY,+ "aws_secret_access_key": "synthetic-store-secret-key",+ "aws_region_name": "us-east-1",+ "aws_bedrock_runtime_endpoint": wire.url,+ },+ },+ )+ scenario.cleanups.callback(gateway.post, "/vector_store/delete", {"vector_store_id": knowledge_base_id})++ response: Final = gateway.request(+ "POST",+ f"/v1/vector_stores/{knowledge_base_id}/search",+ {"query": QUERY, "max_num_results": 3},+ key=team_key,+ )+ assert response.status_code == 200, response.text+ assert JSON_OBJECT.validate_json(response.content)["data"] == [_BEDROCK_RESULT], response.text+ assert len(wire.drain()) == 1+++def test_openai_vector_store_search_without_store_key_uses_team_byok_key(gateway: Gateway) -> None:+ store_id: Final = f"vs_team_{uuid.uuid4().hex}"+ with wire_server(_openai_search_peer(store_id)) as wire, gateway.scenario() as scenario:+ team: Final = scenario.team()+ scenario.model(+ model="openai/gpt-4o-mini",+ api_key="team-openai-key",+ api_base=f"{wire.url}/v1",+ model_info={"team_id": team},+ )+ team_key: Final = scenario.key(team_id=team)+ gateway.post(+ "/vector_store/new",+ {+ "vector_store_id": store_id,+ "custom_llm_provider": "openai",+ "litellm_params": {},+ },+ )+ scenario.cleanups.callback(gateway.post, "/vector_store/delete", {"vector_store_id": store_id})++ response: Final = gateway.request(+ "POST",+ f"/v1/vector_stores/{store_id}/search",+ {"query": QUERY},+ key=team_key,+ )+ assert response.status_code == 200, response.text+ assert JSON_OBJECT.validate_json(response.content)["data"] == [_OPENAI_RESULT], response.text+ assert len(wire.drain()) == 1diff --git a/tests/unit/proxy/test_route_llm_request.py b/tests/unit/proxy/test_route_llm_request.pyindex 67f29220cb6..4e4e2f23950 100644--- a/tests/unit/proxy/test_route_llm_request.py+++ b/tests/unit/proxy/test_route_llm_request.py@@ -1,4 +1,7 @@+import httpx+import litellmimport pytest+import respxfrom types import SimpleNamespace@@ -1890,3 +1893,92 @@ async def test_null_user_config_is_treated_as_absent() -> None:)assert response.choices[0].message.content == "from the main router"+++def _registered_bedrock_kb_search(team_id: str) -> dict[str, object]:+ """The request a team key's /v1/vector_stores/{id}/search carries once the registry row is merged in."""+ return {+ "model": None,+ "vector_store_id": "KB12345678",+ "query": "litellm proxy",+ "custom_llm_provider": "bedrock",+ "aws_region_name": "us-east-1",+ "aws_access_key_id": "AKIAREGISTRYKEY00000",+ "aws_secret_access_key": "registry-secret",+ "metadata": {"user_api_key_team_id": team_id},+ }+++def _team_a_router(*team_models: tuple[str, dict[str, object]]) -> litellm.Router:+ return litellm.Router(+ model_list=[+ {+ "model_name": f"internal-team-a-{public_name}",+ "litellm_params": litellm_params,+ "model_info": {+ "id": f"team-a-{public_name}",+ "team_id": "team-a",+ "team_public_model_name": public_name,+ },+ }+ for public_name, litellm_params in team_models+ ]+ )+++_LANGGRAPH_AGENT_PARAMS: Final[dict[str, object]] = {+ "model": "langgraph/repro-agent",+ "api_base": "http://127.0.0.1:2024",+}+_BEDROCK_CLAUDE_PARAMS: Final[dict[str, object]] = {+ "model": "bedrock/anthropic.claude-sonnet-4-6",+ "aws_region_name": "us-east-1",+}+++ "team_models",+ [+ pytest.param(+ [("a-langgraph-agent", _LANGGRAPH_AGENT_PARAMS), ("a-bedrock-claude", _BEDROCK_CLAUDE_PARAMS)],+ id="langgraph-first",+ ),+ pytest.param(+ [("a-bedrock-claude", _BEDROCK_CLAUDE_PARAMS), ("a-langgraph-agent", _LANGGRAPH_AGENT_PARAMS)],+ id="bedrock-first",+ ),+ pytest.param([("a-langgraph-agent", _LANGGRAPH_AGENT_PARAMS)], id="no-bedrock-team-model"),+ ],+)+async def test_team_key_search_of_registered_bedrock_store_reaches_bedrock_with_registry_credentials(+ monkeypatch: pytest.MonkeyPatch,+ team_models: list[tuple[str, dict[str, object]]],+) -> None:+ """A team key's model-less search of a registered Bedrock store was routed through the team's first+ deployment, so a langgraph team model turned it into "Vector store search is not supported for langgraph"."""++ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)++ with respx.mock(assert_all_called=True) as respx_mock:+ route: Final = respx_mock.post(+ "https://bedrock-agent-runtime.us-east-1.amazonaws.com/knowledgebases/KB12345678/retrieve"+ ).mock(return_value=httpx.Response(200, json={"retrievalResults": []}))+ response: Final = await (+ await route_request(+ _registered_bedrock_kb_search("team-a"),+ _team_a_router(*team_models),+ None,+ "avector_store_search",+ )+ )++ request: Final = route.calls.last.request+ posted_url: Final = str(request.url)+ signed_auth: Final = request.headers["Authorization"]+ assert response["object"] == "vector_store.search_results.page", response+ assert route.call_count == 1+ assert posted_url == "https://bedrock-agent-runtime.us-east-1.amazonaws.com/knowledgebases/KB12345678/retrieve", (+ posted_url+ )+ assert "Credential=AKIAREGISTRYKEY00000/" in signed_auth, signed_authdiff --git a/tests/unit/test_router/test_router.py b/tests/unit/test_router/test_router.pyindex 50a9d98385d..bd3cf738af8 100644--- a/tests/unit/test_router/test_router.py+++ b/tests/unit/test_router/test_router.py@@ -23912,6 +23912,105 @@ def test_map_team_model_should_not_iterate_aliases_for_non_alias_team_model_nameresult = router.map_team_model(team_model_name="team-model", team_id="team-1")assert result == "team-model", f"Expected public name 'team-model', got {result}"++def _team_deployment(+ public_name: str,+ litellm_model: str,+ team_id: str = "team-a",+ deployment_id: str | None = None,+) -> DeploymentTypedDict:+ return {+ "model_name": f"internal-{team_id}-{public_name}",+ "litellm_params": {"model": litellm_model},+ "model_info": {+ "id": deployment_id or f"{team_id}-{public_name}",+ "team_id": team_id,+ "team_public_model_name": public_name,+ },+ }+++_LANGGRAPH_AGENT: Final[DeploymentTypedDict] = _team_deployment("a-langgraph-agent", "langgraph/repro-agent")+_BEDROCK_CLAUDE: Final[DeploymentTypedDict] = _team_deployment(+ "a-bedrock-claude", "bedrock/anthropic.claude-sonnet-4-6"+)+_OPENAI_GPT: Final[DeploymentTypedDict] = _team_deployment("a-gpt", "openai/gpt-4o-mini")+++ "team_models, custom_llm_provider, expected",+ [+ pytest.param([_LANGGRAPH_AGENT, _BEDROCK_CLAUDE], "bedrock", "a-bedrock-claude", id="match-is-second"),+ pytest.param([_BEDROCK_CLAUDE, _LANGGRAPH_AGENT], "bedrock", "a-bedrock-claude", id="match-is-first"),+ pytest.param([_LANGGRAPH_AGENT, _OPENAI_GPT], "bedrock", None, id="no-match-returns-none"),+ pytest.param([_LANGGRAPH_AGENT, _BEDROCK_CLAUDE], None, "a-langgraph-agent", id="no-provider-keeps-first"),+ pytest.param(+ [_team_deployment("b-bedrock-claude", "bedrock/anthropic.claude-sonnet-4-6", team_id="team-b")],+ "bedrock",+ None,+ id="other-teams-match-ignored",+ ),+ pytest.param(+ [+ _team_deployment("shared", "langgraph/repro-agent", deployment_id="shared-langgraph"),+ _team_deployment(+ "shared",+ "bedrock/anthropic.claude-sonnet-4-6",+ deployment_id="shared-bedrock",+ ),+ ],+ "bedrock",+ "shared-bedrock",+ id="mixed-public-name-langgraph-first",+ ),+ pytest.param(+ [+ _team_deployment(+ "shared",+ "bedrock/anthropic.claude-sonnet-4-6",+ deployment_id="shared-bedrock",+ ),+ _team_deployment("shared", "langgraph/repro-agent", deployment_id="shared-langgraph"),+ ],+ "bedrock",+ "shared-bedrock",+ id="mixed-public-name-bedrock-first",+ ),+ pytest.param(+ [+ _team_deployment("shared", "bedrock/anthropic.claude-sonnet-4-6", deployment_id="bedrock-one"),+ _team_deployment("shared", "bedrock/anthropic.claude-sonnet-4-6", deployment_id="bedrock-two"),+ ],+ "bedrock",+ "shared",+ id="same-provider-public-name-keeps-load-balancing",+ ),+ ],+)+def test_map_team_model_without_model_picks_deployment_serving_the_requested_provider(+ team_models: list[DeploymentTypedDict], custom_llm_provider: str | None, expected: str | None+) -> None:+ """A model-less vector store call routed through the team's first deployment, so a langgraph+ team model made a Bedrock vector store search fail with "not supported for langgraph"."""+ router = Router(model_list=team_models)++ result = router.map_team_model(None, "team-a", custom_llm_provider=custom_llm_provider)++ assert result == expected, (+ f"team models {[m['litellm_params']['model'] for m in team_models]}, provider {custom_llm_provider}"+ )+++def test_map_team_model_with_explicit_model_ignores_requested_provider() -> None:+ router = Router(model_list=[_LANGGRAPH_AGENT, _BEDROCK_CLAUDE])++ result = router.map_team_model("a-langgraph-agent", "team-a", custom_llm_provider="bedrock")++ assert result == "a-langgraph-agent", (+ "an explicit model is the caller's choice and must not be re-picked by provider"+ )++@pytest.mark.usefixtures("_vcr_outcome_gate_router_unit", "setup_and_teardown_router_unit")class TestPreCallChecksOptimization:"""