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(rag)!: use team provider credentials and allow viewer and JWT team access (#45497)
Shivam Rawatc58fc0c99638
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex a7bd16804c1..5970ede5c7e 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -4829,6 +4829,10 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):"mcp_routes","/v1/messages","/v1/messages/count_tokens",+ "/rag/ingest",+ "/v1/rag/ingest",+ "/rag/query",+ "/v1/rag/query",]team_id_default: str | None = Field(default=None,diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex b395a826625..d0708fcda2f 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -4784,7 +4784,7 @@ def check_model_access_helper(if _model_in_team_aliases(model=model, team_model_aliases=team_model_aliases):return True- if _model_matches_any_wildcard_pattern_in_list(model=model, allowed_model_list=filtered_models):+ if model_matches_any_wildcard_pattern_in_list(model=model, allowed_model_list=filtered_models):return Trueall_model_access: bool = False@@ -7434,7 +7434,7 @@ def is_model_allowed_by_pattern(model: str, allowed_model_pattern: str) -> bool:return False-def _model_matches_any_wildcard_pattern_in_list(model: str, allowed_model_list: list) -> bool:+def model_matches_any_wildcard_pattern_in_list(model: str, allowed_model_list: Sequence[str]) -> bool:"""Returns True if a model matches any wildcard pattern in a list.diff --git a/litellm/proxy/auth/handle_jwt.py b/litellm/proxy/auth/handle_jwt.pyindex 05b8cca19af..9d800a1fd63 100644--- a/litellm/proxy/auth/handle_jwt.py+++ b/litellm/proxy/auth/handle_jwt.py@@ -1767,6 +1767,7 @@ class JWTAuthManager:from litellm.proxy.proxy_server import llm_routerdenied_pass_through_team: LiteLLM_TeamTable | None = None+ route_denied_team_id: str | None = None # rebind-ok: retain route-denied team while checking all claimsif not team_ids:if (@@ -1780,7 +1781,7 @@ class JWTAuthManager:return None, Noneany_claim_team_resolved = False- for team_id in team_ids:+ for team_id in sorted(team_ids, key=str):try:team_object = await get_team_object(team_id=team_id,@@ -1809,7 +1810,9 @@ class JWTAuthManager:user_route=route,litellm_proxy_roles=jwt_handler.litellm_jwtauth,)- if is_allowed and not JWTAuthManager._team_has_passthrough_route_access(+ if not is_allowed:+ route_denied_team_id = team_id+ elif not JWTAuthManager._team_has_passthrough_route_access(team_object=team_object,route=route,request_method=request_method,@@ -1832,7 +1835,13 @@ class JWTAuthManager:# Claim resolved but no model access, or fallback disabled — deny.raise HTTPException(status_code=403,- detail=f"No team has access to the requested model: {requested_model}. Checked teams={team_ids}. Check `/models` to see all available models.",+ detail=(+ f"Team {route_denied_team_id} can access model {requested_model} but route {route} "+ "is not in litellm_jwtauth.team_allowed_routes"+ if route_denied_team_id is not None+ else f"No team has access to the requested model: {requested_model}. "+ f"Checked teams={team_ids}. Check `/models` to see all available models."+ ),)# No claim team resolved and fallback enabled — defer to fallback.@@ -2003,7 +2012,7 @@ class JWTAuthManager:status_code=403,detail=(f"x-litellm-team-id '{header_value}' does not resolve to a team id or a unique team alias in your "- f"JWT's allowed teams. Allowed team ids: {sorted(allowed_team_ids)}"+ f"JWT's allowed teams. Allowed team ids: {sorted(allowed_team_ids, key=str)}"),)diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.pyindex ead1cd8e2ca..763737191ef 100644--- a/litellm/proxy/batches_endpoints/endpoints.py+++ b/litellm/proxy/batches_endpoints/endpoints.py@@ -149,6 +149,14 @@ async def _raise_when_input_file_must_be_managed(model: str, credentials: Mappin)+def _raise_when_routing_headers_disagree(request: Request, body_model: object) -> None:+ if (isinstance(body_model, str) and body_model) or request.query_params.get("model"):+ return+ if len(frozenset(request.headers.getlist("x-litellm-model"))) < 2:+ return+ raise batch_error(400, "Send one x-litellm-model header. This request has several naming different models")++def _litellm_metadata_of(data: MutableMapping[str, object]) -> MutableMapping[str, object]:"""The request's litellm_metadata mapping, created on the request when it carries none.@@ -274,6 +282,7 @@ async def create_batch(data: dict = {}try:data = await read_request_body(request=request) # rebind-ok: pre-existing rebinding on a rename-only line+ _raise_when_routing_headers_disagree(request, data.get("model"))verbose_proxy_logger.debug("Request received by LiteLLM:\n%s",json.dumps(data, indent=4),diff --git a/litellm/proxy/hooks/batch_rate_limiter.py b/litellm/proxy/hooks/batch_rate_limiter.pyindex 5f214816578..94762232e0b 100644--- a/litellm/proxy/hooks/batch_rate_limiter.py+++ b/litellm/proxy/hooks/batch_rate_limiter.py@@ -22,6 +22,7 @@ from collections.abc import Callable, Iterable, Mapping, Sequencefrom datetime import datetime, timezonefrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, Literal, NoReturn, TypeAlias+from urllib.parse import parse_qs, urlsplitfrom fastapi import HTTPExceptionfrom pydantic import Field, TypeAdapter, ValidationError@@ -99,6 +100,28 @@ else:_BATCH_BODY_ADAPTER: Final = TypeAdapter(dict[str, object])_WINDOW_START_ADAPTER: Final[TypeAdapter[int | float | str | None]] = TypeAdapter(int | float | str | None)++def _batch_create_routing_model(data: Mapping[str, object]) -> str | None:+ body_model: Final = data.get("model")+ if isinstance(body_model, str) and body_model:+ return body_model+ proxy_server_request: Final = data.get("proxy_server_request")+ if not isinstance(proxy_server_request, Mapping):+ return None+ request_line: Final = _BATCH_BODY_ADAPTER.validate_python(proxy_server_request)+ url: Final = request_line.get("url")+ query_model: Final = (+ parse_qs(urlsplit(url).query, keep_blank_values=True).get("model", [None])[-1] if isinstance(url, str) else None+ )+ if query_model:+ return query_model+ headers: Final = request_line.get("headers")+ header_model: Final = (+ _BATCH_BODY_ADAPTER.validate_python(headers).get("x-litellm-model") if isinstance(headers, Mapping) else None+ )+ return header_model if isinstance(header_model, str) and header_model else None++IncrementAmounts: TypeAlias = dict[Literal["requests", "tokens"], int]@@ -509,6 +532,7 @@ class _PROXY_BatchRateLimiter(CustomLogger):file_id: str,custom_llm_provider: str,data: dict,+ user_api_key_dict: UserAPIKeyAuth | None = None,) -> tuple[str, dict[str, Any]]:"""Map proxy-facing file IDs to provider file IDs and credentials.@@ -519,8 +543,10 @@ class _PROXY_BatchRateLimiter(CustomLogger):"""from litellm.proxy.openai_files_endpoints.common_utils import (decode_model_from_file_id,+ explicit_request_credentials,get_credentials_for_model,get_original_file_id,+ get_team_provider_credentials,)from litellm.proxy.proxy_server import llm_router@@ -546,22 +572,36 @@ class _PROXY_BatchRateLimiter(CustomLogger):passreturn get_original_file_id(file_id), fetch_kwargs- request_model: Final = data.get("model")- if isinstance(request_model, str) and request_model and llm_router is not None:- try:- credentials = get_credentials_for_model(- llm_router=llm_router,- model_id=request_model,- operation_context="batch input file read (rate limiting)",- )- fetch_kwargs.update(extract_file_access_credentials(credentials))- fetch_kwargs["model"] = request_model- provider = credentials.get("custom_llm_provider")- if provider:- fetch_kwargs["custom_llm_provider"] = provider- except HTTPException:- pass+ request_model: Final = _batch_create_routing_model(data)+ if request_model is not None:+ if llm_router is not None:+ try:+ credentials = get_credentials_for_model(+ llm_router=llm_router,+ model_id=request_model,+ operation_context="batch input file read (rate limiting)",+ )+ fetch_kwargs.update(extract_file_access_credentials(credentials))+ fetch_kwargs["model"] = request_model+ provider = credentials.get("custom_llm_provider")+ if provider:+ fetch_kwargs["custom_llm_provider"] = provider+ except HTTPException:+ pass+ return file_id, fetch_kwargs+ team_credentials: Final = (+ get_team_provider_credentials(+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )+ if user_api_key_dict is not None+ else None+ )+ fetch_kwargs.update(+ extract_file_access_credentials({**(team_credentials or {}), **explicit_request_credentials(data)})+ )return file_id, fetch_kwargsasync def _reserve_batch_enqueued_tokens(@@ -912,6 +952,7 @@ class _PROXY_BatchRateLimiter(CustomLogger):file_id=file_id,custom_llm_provider=custom_llm_provider,data=data or {},+ user_api_key_dict=user_api_key_dict,)# For non-managed files, use the standard litellm.afile_contentfile_content = await litellm.afile_content(diff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.pyindex 48306cc8d7a..2e07694876b 100644--- a/litellm/proxy/openai_files_endpoints/common_utils.py+++ b/litellm/proxy/openai_files_endpoints/common_utils.py@@ -4,6 +4,7 @@ import mimetypesimport refrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass, field+from datetime import datetime, timezonefrom types import MappingProxyTypefrom typing import (TYPE_CHECKING,@@ -17,6 +18,7 @@ from typing import ()from pydantic import TypeAdapter+from typing_extensions import NotRequired, ReadOnly, TypedDictfrom litellm.batches.batch_utils import batch_cost_is_finalfrom litellm.constants import MAX_FILE_LIST_LIMIT@@ -43,6 +45,7 @@ FILE_LIST_CONTINUATION_CHUNK_SIZE: Final = 500BATCH_CREATE_HIDDEN_PARAM: Final = "batch_create"LITELLM_EXECUTED_BATCH_ID_PREFIX: Final = "litellm_batch_"+EXPLICIT_CREDENTIAL_KEYS: Final = frozenset({"api_key", "api_base", "litellm_credential_name"})def validate_file_list_limit(limit: int | None) -> None:@@ -474,10 +477,47 @@ async def get_authorized_credentials_for_model()+def _key_allowlist_covers(public_model_name: str, key_model_allowlist: Sequence[str]) -> bool:+ from litellm.proxy.auth.auth_checks import model_matches_any_wildcard_pattern_in_list++ if public_model_name in key_model_allowlist:+ return True+ if model_matches_any_wildcard_pattern_in_list(model=public_model_name, allowed_model_list=key_model_allowlist):+ return True+ return any(+ model_matches_any_wildcard_pattern_in_list(model=key_model, allowed_model_list=(public_model_name,))+ for key_model in key_model_allowlist+ )+++_CONFIG_FILE_RANK: Final = datetime.min.replace(tzinfo=timezone.utc)+_UNKNOWN_CREATION_TIME: Final = datetime.max.replace(tzinfo=timezone.utc)+++class _RouterDeployment(TypedDict):+ model_name: ReadOnly[NotRequired[str]]+ model_info: ReadOnly[Mapping[str, object]]+++def _team_deployment_rank(model_info: Mapping[str, object], deployment_id: str) -> tuple[datetime, str]:+ if model_info.get("db_model") is not True:+ return _CONFIG_FILE_RANK, ""+ created_at: Final = model_info.get("created_at")+ if not isinstance(created_at, datetime):+ return _UNKNOWN_CREATION_TIME, deployment_id+ return (created_at if created_at.tzinfo else created_at.replace(tzinfo=timezone.utc)), deployment_id+++def _by_team_deployment_rank(order: tuple[tuple[datetime, str], str]) -> tuple[datetime, str]:+ return order[0]++def get_team_provider_credentials(llm_router: Optional["Router"],user_api_key_dict: "UserAPIKeyAuth",custom_llm_provider: str,+ *,+ include_accessible_deployments: bool = True,) -> dict | None:"""Resolve upstream credentials for a provider-scoped file operation@@ -490,12 +530,15 @@ def get_team_provider_credentials(global one.2. Fallback: any deployment the caller is granted access to for thisprovider, expanding wildcard routes and the all-proxy-models sentinel.+ Skipped when ``include_accessible_deployments`` is False.Credential lookup is scoped to both the team's allowlist and the key's ownmodel allowlist (``user_api_key_dict.models``), so neither a team nor arestricted key within a team can resolve a provider key for a deploymentit isn't authorized to use. A key restricted to an explicit model list- only narrows the team scope; sentinel-bearing keys (all-proxy-models /+ only narrows the team scope, matching a wildcard on either side the way+ request authorization does (a key allowed ``gpt-4o`` may use the team's+ ``openai/*`` deployment); sentinel-bearing keys (all-proxy-models /all-team-models) defer to the team scope instead of widening past it.Returns None when the router is unavailable or no authorized deploymentmatches, so the caller can fall back to default credential resolution.@@ -531,33 +574,52 @@ def get_team_provider_credentials(if key_is_restrictedelse ())- key_model_allowlist_set: Final = frozenset(key_model_allowlist)- def _key_may_use(public_model_name: str | None) -> bool:- if not key_model_allowlist_set:+ def _key_may_use(public_model_name: object) -> bool:+ if not key_model_allowlist:return True- return public_model_name is not None and public_model_name in key_model_allowlist_set+ return isinstance(public_model_name, str) and _key_allowlist_covers(public_model_name, key_model_allowlist)- def _provider_credentials(model_id: str) -> dict | None:+ def _provider_credentials(model_id: str) -> dict[str, object] | None:credentials: Final = llm_router.get_deployment_credentials_with_provider(model_id=model_id, team_id=team_id)if credentials is not None and credentials.get("custom_llm_provider") == custom_llm_provider:return {key: value for key, value in credentials.items() if key != "model"}return None- # 1. Prefer the team's own BYOK deployment, matched by model_info.team_id.+ def _usable_team_deployment_order(deployment: _RouterDeployment) -> tuple[tuple[datetime, str], str] | None:+ model_info: Final[Mapping[str, object]] = deployment["model_info"]+ if model_info.get("team_id") != team_id:+ return None+ if not _key_may_use(model_info.get("team_public_model_name") or deployment.get("model_name")):+ return None+ deployment_id: Final = model_info.get("id")+ if not isinstance(deployment_id, str):+ return None+ return _team_deployment_rank(model_info, deployment_id), deployment_id++ # 1. Prefer the team's own BYOK deployment, matched by model_info.team_id. Config file+ # deployments win, kept in file order by the stable sort, then DB ones oldest first, then+ # by lowest id, so adding a deployment never moves the team off the one it already uses,+ # and every worker picks the same one in any DB load or edit order.if team_id is not None:- for deployment in llm_router.model_list or []:- model_info = deployment.get("model_info") or {}- if model_info.get("team_id") != team_id:- continue- deployment_id = model_info.get("id")- if deployment_id is None:- continue- if not _key_may_use(model_info.get("team_public_model_name") or deployment.get("model_name")):- continue- credentials = _provider_credentials(deployment_id)- if credentials is not None:- return credentials+ team_deployment_orders: Final = sorted(+ (+ order+ for deployment in llm_router.model_list or []+ if (order := _usable_team_deployment_order(deployment)) is not None+ ),+ key=_by_team_deployment_rank,+ )+ team_deployment_ids: Final = tuple(deployment_id for _, deployment_id in team_deployment_orders)+ team_credentials: Final = next(+ (credentials for credentials in map(_provider_credentials, team_deployment_ids) if credentials is not None),+ None,+ )+ if team_credentials is not None:+ return team_credentials++ if not include_accessible_deployments:+ return None# 2. Fall back to deployments the caller is allowed to access. The key's# effective allowlist (sentinels and access groups already expanded by@@ -594,6 +656,42 @@ def get_team_provider_credentials(return None+HTTP_HEADER_VALUE: Final = re.compile(r"[\x21-\x7e]+(?:[ \t]+[\x21-\x7e]+)*")+++def _non_blank_string(value: object) -> str | None:+ return value if isinstance(value, str) and value.strip() else None+++def _request_api_key(data: Mapping[str, object]) -> str | None:+ from fastapi import HTTPException++ import litellm++ api_key: Final = _non_blank_string(data.get("api_key"))+ if api_key is None or HTTP_HEADER_VALUE.fullmatch(api_key):+ return api_key+ if data.get("drop_params") is True or litellm.drop_params is True:+ return None+ raise HTTPException(+ status_code=400,+ detail={+ "error": "The request's provider api_key is not a valid HTTP header value. Remove surrounding "+ "whitespace and non-ASCII characters, or set drop_params to send the request without it."+ },+ )+++def explicit_request_credentials(data: Mapping[str, object]) -> Mapping[str, str]:+ api_key: Final = _request_api_key(data)+ if api_key is None:+ return MappingProxyType({})+ api_base: Final = _non_blank_string(data.get("api_base"))+ if api_base is None:+ return MappingProxyType({"api_key": api_key})+ return MappingProxyType({"api_key": api_key, "api_base": api_base})++def apply_team_provider_credentials(data: dict, # mutable-ok: credentials are merged into the request payload in place, same contract as prepare_data_with_credentialsllm_router: Optional["Router"],@@ -605,6 +703,9 @@ def apply_team_provider_credentials(``get_team_provider_credentials`` and merge them into ``data`` in-place.Leaves ``data`` untouched when no authorized deployment matches, so thecaller falls back to environment-variable credentials exactly as before.+ An ``api_key`` the request carries itself (a provider key forwarded with+ ``forward_llm_provider_auth_headers``) replaces the deployment's, and the+ request's ``api_base`` replaces the deployment's only alongside that key."""credentials: Final = get_team_provider_credentials(llm_router=llm_router,@@ -613,7 +714,7 @@ def apply_team_provider_credentials()if credentials is None:return- prepare_data_with_credentials(data=data, credentials=credentials)+ prepare_data_with_credentials(data=data, credentials={**credentials, **explicit_request_credentials(data)})def add_internal_model_credentials(diff --git a/litellm/proxy/rag_endpoints/endpoints.py b/litellm/proxy/rag_endpoints/endpoints.pyindex a1a7d62899f..a7146f13035 100644--- a/litellm/proxy/rag_endpoints/endpoints.py+++ b/litellm/proxy/rag_endpoints/endpoints.py@@ -13,8 +13,9 @@ from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Finalimport orjson-from fastapi import APIRouter, Depends, HTTPException, Request, Response, status+from fastapi import APIRouter, Depends, HTTPException, Request, Responsefrom fastapi.responses import ORJSONResponse, StreamingResponse+from pydantic import TypeAdapterfrom starlette.datastructures import UploadFileimport litellm@@ -38,6 +39,11 @@ from litellm.proxy.common_utils.http_parsing_utils import ( # noqa: F401 # legread_request_body,safe_get_request_headers,)+from litellm.proxy.openai_files_endpoints.common_utils import (+ EXPLICIT_CREDENTIAL_KEYS,+ explicit_request_credentials,+ get_team_provider_credentials,+)from litellm.proxy.rag_endpoints.upload_security import (MAX_UPLOAD_SIZE_BYTES,EicarTestMalwareScanner,@@ -57,9 +63,13 @@ from litellm.repositories.table_repositories import ManagedVectorStoresRepositorfrom litellm.types.utils import ModelResponseif TYPE_CHECKING:+ from litellm import Routerfrom litellm.proxy.utils import PrismaClientrouter: Final = APIRouter()+_TEAM_PROVIDER_CREDENTIALS_ADAPTER: Final = TypeAdapter(dict[str, object])+_EMPTY_TEAM_PROVIDER_CREDENTIALS: Final[Mapping[str, object]] = MappingProxyType({})+_TEAM_CREDENTIAL_PROVIDER: Final = "openai"def _as_string_keyed_mapping(value: object) -> Mapping[str, object] | None:@@ -186,21 +196,91 @@ def _caller_vector_store_options(managed_store: LiteLLM_ManagedVectorStore | None,) -> Mapping[str, object]:if managed_store is None:- return request_vector_store_config+ return _without_blank_credentials(request_vector_store_config)return MappingProxyType({key: value for key, value in request_vector_store_config.items() if key in _MANAGED_STORE_CALLER_OPTIONS})+def _is_blank(value: object) -> bool:+ return value is None or (isinstance(value, str) and not value.strip())+++def _without_blank_credentials(config: Mapping[str, object]) -> Mapping[str, object]:+ return MappingProxyType(+ {key: value for key, value in config.items() if key not in EXPLICIT_CREDENTIAL_KEYS or not _is_blank(value)}+ )+++def _store_provider(config: Mapping[str, object]) -> object:+ provider: Final = config.get("custom_llm_provider")+ return _TEAM_CREDENTIAL_PROVIDER if provider is None else provider++def _managed_store_overrides(managed_store: LiteLLM_ManagedVectorStore | None) -> Mapping[str, object]:if managed_store is None:return MappingProxyType({})+ stored: Final = build_request_data_from_managed_vector_store(managed_store)+ return _without_blank_credentials({key: value for key, value in stored.items() if value is not None})+++def _forwarded_store_credentials(+ vector_store_config: Mapping[str, object], request_data: Mapping[str, object]+) -> Mapping[str, object]:+ if _store_provider(vector_store_config) != _TEAM_CREDENTIAL_PROVIDER:+ return _EMPTY_TEAM_PROVIDER_CREDENTIALS+ return explicit_request_credentials(request_data)+++def _with_body_drop_params(request_data: Mapping[str, object], body: Mapping[str, object]) -> Mapping[str, object]:+ if body.get("drop_params") is not True:+ return request_data+ return MappingProxyType({**request_data, "drop_params": True})+++async def _rag_ingest_body(request: Request) -> Mapping[str, object]:+ body: Final = _TEAM_PROVIDER_CREDENTIALS_ADAPTER.validate_python(await read_request_body(request))+ if "multipart/form-data" not in request.headers.get("content-type", ""):+ return body+ form_request: Final = body.get("request")+ parsed: Final[object] = (+ orjson.loads(form_request) if isinstance(form_request, (str, bytes)) and form_request else None+ )+ return (+ _TEAM_PROVIDER_CREDENTIALS_ADAPTER.validate_python(parsed) if isinstance(parsed, dict) else MappingProxyType({})+ )+++def _with_request_credentials(+ team_credentials: Mapping[str, object], request_data: Mapping[str, object]+) -> Mapping[str, object]:+ if not team_credentials:+ return team_credentials+ return MappingProxyType({**team_credentials, **explicit_request_credentials(request_data)})+++def _team_provider_credentials(+ effective_config: Mapping[str, object],+ llm_router: "Router | None",+ user_api_key_dict: UserAPIKeyAuth,+) -> Mapping[str, object]:+ if not EXPLICIT_CREDENTIAL_KEYS.isdisjoint(effective_config):+ return _EMPTY_TEAM_PROVIDER_CREDENTIALS++ if _store_provider(effective_config) != _TEAM_CREDENTIAL_PROVIDER:+ return _EMPTY_TEAM_PROVIDER_CREDENTIALS++ validated_credentials: Final = _TEAM_PROVIDER_CREDENTIALS_ADAPTER.validate_python(+ get_team_provider_credentials(+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=_TEAM_CREDENTIAL_PROVIDER,+ include_accessible_deployments=False,+ )+ or {}+ )return MappingProxyType(- {- key: value- for key, value in build_request_data_from_managed_vector_store(managed_store).items()- if value is not None- }+ {key: value for key, value in validated_credentials.items() if key not in {"custom_llm_provider", "model"}})@@ -591,18 +671,6 @@ async def rag_ingest(request, scanner=EicarTestMalwareScanner())- # INTERNAL_USER_VIEW_ONLY can ingest to existing vector stores only- if user_api_key_dict.user_role == LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value and not ingest_options.get(- "vector_store", {}- ).get("vector_store_id"):- raise HTTPException(- status_code=status.HTTP_403_FORBIDDEN,- detail={- "error": "internal_user_viewer role can only ingest files to an existing vector store. "- "Provide 'vector_store_id' in ingest_options.vector_store."- },- )-resolved_stores: Final = await _authorize_nested_vector_store_ids(payload=ingest_options,user_api_key_dict=user_api_key_dict,@@ -620,10 +688,26 @@ async def rag_ingest(raise HTTPException(status_code=400, detail={"error": str(e)})managed_store: Final = resolved_stores.get(request_vector_store_config.get("vector_store_id"))- merged_vector_store_config: Final = {+ base: Final = {**_caller_vector_store_options(request_vector_store_config, managed_store),**_managed_store_overrides(managed_store),}+ request_data: Final[dict[str, Any]] = await add_litellm_data_to_request(+ data={},+ request=request,+ general_settings=general_settings,+ user_api_key_dict=user_api_key_dict,+ version=version,+ proxy_config=proxy_config,+ )+ forwarded_credentials: Final = _forwarded_store_credentials(+ base, _with_body_drop_params(request_data, await _rag_ingest_body(request))+ )+ merged_vector_store_config: Final = {+ **_team_provider_credentials(base, llm_router, user_api_key_dict),+ **forwarded_credentials,+ **base,+ }merged_ingest_options: Final = {**ingest_options,"vector_store": merged_vector_store_config,@@ -636,17 +720,6 @@ async def rag_ingest(detail={"error": provider_error},)- # Add litellm data- request_data: dict[str, Any] = {}- request_data = await add_litellm_data_to_request(- data=request_data,- request=request,- general_settings=general_settings,- user_api_key_dict=user_api_key_dict,- version=version,- proxy_config=proxy_config,- )-verbose_proxy_logger.debug("RAG Ingest - options: %s, custom_llm_provider: %s",ingest_options,@@ -662,6 +735,11 @@ async def rag_ingest(router=llm_router,**request_data,)+ if response.get("status") == "failed":+ raise HTTPException(+ status_code=response.get("error_status_code") or 500,+ detail={"id": response.get("id"), "status": "failed", "error": response.get("error")},+ )# Save vector store to database if it was newly created and prisma_client is availableverbose_proxy_logger.debug(@@ -777,7 +855,7 @@ async def rag_query(# Extract required fieldsmodel: Final = data.get("model")messages: Final = data.get("messages")- retrieval_config: Final = data.get("retrieval_config")+ raw_retrieval_config: Final = data.get("retrieval_config")rerank: Final = data.get("rerank")stream: Final = data.get("stream", False)@@ -792,21 +870,28 @@ async def rag_query(status_code=400,detail={"error": "messages is required"},)- if not retrieval_config:+ if not raw_retrieval_config:raise HTTPException(status_code=400,detail={"error": "retrieval_config is required"},)- if not isinstance(retrieval_config, dict):+ if not isinstance(raw_retrieval_config, dict):raise HTTPException(status_code=400,detail={"error": "retrieval_config must be an object"},)+ retrieval_config: Final = _TEAM_PROVIDER_CREDENTIALS_ADAPTER.validate_python(raw_retrieval_config)if "vector_store_id" not in retrieval_config:raise HTTPException(status_code=400,detail={"error": "retrieval_config must contain 'vector_store_id'"},)+ vector_store_id: Final = retrieval_config.get("vector_store_id")+ if not isinstance(vector_store_id, str):+ raise HTTPException(+ status_code=400,+ detail={"error": "vector_store_id must be a non-empty string"},+ )reject_caller_embedding_selection_params(payload=retrieval_config, source="retrieval_config")resolved_stores: Final = await _authorize_nested_vector_store_ids(payload=retrieval_config,@@ -817,27 +902,39 @@ async def rag_query(# model, credentials, ...) from the registry: the same source the direct# /vector_stores/{id}/search endpoint uses. Store-managed keys win on# conflict so callers cannot override the store's provider or credentials.- managed_store: Final = resolved_stores.get(retrieval_config["vector_store_id"])- store_data: Final = (+ managed_store: Final = resolved_stores.get(vector_store_id)+ store_data: Final[Mapping[str, object]] = (build_request_data_from_managed_vector_store(managed_store)if managed_store is not None- else MappingProxyType({})+ else _EMPTY_TEAM_PROVIDER_CREDENTIALS)+ managed_store_params: Final = _managed_store_overrides(managed_store)merged_retrieval_config: Final = {**retrieval_config,**store_data,}-- # Add litellm data- request_data: dict[str, object] = {}- request_data = await add_litellm_data_to_request(- data=request_data,+ effective_vector_store_config: Final = (+ managed_store_params+ if managed_store is not None+ else MappingProxyType(+ {key: value for key, value in retrieval_config.items() if key not in EXPLICIT_CREDENTIAL_KEYS}+ )+ )+ request_data: Final[dict[str, object]] = await add_litellm_data_to_request(+ data={},request=request,general_settings=general_settings,user_api_key_dict=user_api_key_dict,version=version,proxy_config=proxy_config,)+ team_credentials: Final = _with_request_credentials(+ _team_provider_credentials(effective_vector_store_config, llm_router, user_api_key_dict),+ _with_body_drop_params(request_data, data),+ )+ vector_store_params: Final = (+ {**team_credentials, **managed_store_params} if managed_store is not None else team_credentials+ )verbose_proxy_logger.debug("RAG Query - model: %s, vector_store_id: %s, custom_llm_provider: %s",@@ -851,7 +948,7 @@ async def rag_query(model=model,messages=messages,retrieval_config=merged_retrieval_config,- vector_store_params=store_data,+ vector_store_params=vector_store_params,rerank=rerank,stream=stream,router=llm_router,diff --git a/litellm/rag/ingestion/base_ingestion.py b/litellm/rag/ingestion/base_ingestion.pyindex f9e39e042f1..8b2cf6e0a4e 100644--- a/litellm/rag/ingestion/base_ingestion.py+++ b/litellm/rag/ingestion/base_ingestion.py@@ -34,6 +34,10 @@ if TYPE_CHECKING:from litellm import Router+class RAGIngestBadRequestError(ValueError):+ status_code: Final = 400++class BaseRAGIngestion(ABC):"""Base class for RAG ingestion.@@ -319,13 +323,18 @@ class BaseRAGIngestion(ABC):file_id=file_id,)- try:- if existing_file_id and not self.supports_existing_file_id:- raise ValueError(- f"{self.__class__.__name__} does not support ingesting an existing file_id. "- "Upload file data or provide file_url instead."- )+ if existing_file_id and not self.supports_existing_file_id:+ return RAGIngestResponse(+ id=self.ingest_id,+ status="failed",+ vector_store_id="",+ file_id=None,+ error=f"{self.__class__.__name__} does not support ingesting an existing file_id. "+ "Upload file data or provide file_url instead.",+ error_status_code=400,+ )+ try:# Step 2: OCR (optional)extracted_text: Final = await self.ocr(file_content=file_content,@@ -361,10 +370,12 @@ class BaseRAGIngestion(ABC):except Exception as e:verbose_logger.exception("RAG Pipeline failed: %s", e)+ error_status_code: Final[object] = getattr(e, "status_code", None)return RAGIngestResponse(id=self.ingest_id,status="failed",vector_store_id="",file_id=None,error=str(e),+ error_status_code=error_status_code if isinstance(error_status_code, int) else None,)diff --git a/litellm/rag/ingestion/bedrock_ingestion.py b/litellm/rag/ingestion/bedrock_ingestion.pyindex e412b7bcc8d..1e7aa6ac1c6 100644--- a/litellm/rag/ingestion/bedrock_ingestion.py+++ b/litellm/rag/ingestion/bedrock_ingestion.py@@ -19,7 +19,7 @@ from typing import TYPE_CHECKING, Finalfrom litellm._logging import verbose_loggerfrom litellm.litellm_core_utils.aws_partition import get_aws_arn_prefixfrom litellm.llms.bedrock.base_aws_llm import BaseAWSLLM-from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion, RAGIngestBadRequestErrorif TYPE_CHECKING:from litellm import Router@@ -149,7 +149,7 @@ class BedrockRAGIngestion(BaseRAGIngestion, BaseAWSLLM):data_sources: Final = ds_response.get("dataSourceSummaries", [])if not data_sources:- raise ValueError(+ raise RAGIngestBadRequestError(f"No data sources found for Knowledge Base {self.knowledge_base_id}. ""Please create a data source first or provide data_source_id and s3_bucket.")@@ -181,7 +181,7 @@ class BedrockRAGIngestion(BaseRAGIngestion, BaseAWSLLM):self.s3_prefix = prefixes[0]else:if not self._s3_bucket:- raise ValueError(+ raise RAGIngestBadRequestError(f"Could not auto-detect S3 bucket for data source {self.data_source_id}. ""Please provide s3_bucket in config.")diff --git a/litellm/rag/ingestion/openai_ingestion.py b/litellm/rag/ingestion/openai_ingestion.pyindex 6c7c619237d..e6a3f0bb74f 100644--- a/litellm/rag/ingestion/openai_ingestion.py+++ b/litellm/rag/ingestion/openai_ingestion.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Finalimport litellm-from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion, RAGIngestBadRequestErrorfrom litellm.vector_store_files.main import acreate as vector_store_file_acreatefrom litellm.vector_stores.main import acreate as vector_store_acreate@@ -87,7 +87,7 @@ class OpenAIRAGIngestion(BaseRAGIngestion):api_base: Final = self.vector_store_config.get("api_base")if existing_file_id and not vector_store_id:- raise ValueError("vector_store_id is required when ingesting an existing file_id")+ raise RAGIngestBadRequestError("vector_store_id is required when ingesting an existing file_id")# Create vector store if not providedif not vector_store_id:diff --git a/litellm/rag/ingestion/s3_vectors_ingestion.py b/litellm/rag/ingestion/s3_vectors_ingestion.pyindex e3eafd680de..f31b068e709 100644--- a/litellm/rag/ingestion/s3_vectors_ingestion.py+++ b/litellm/rag/ingestion/s3_vectors_ingestion.py@@ -37,7 +37,7 @@ from litellm.llms.s3_vectors.vector_stores.transformation import (s3_vectors_ingest_embedding_options,s3_vectors_ingest_target,)-from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion, RAGIngestBadRequestErrorif TYPE_CHECKING:import httpx@@ -269,13 +269,13 @@ class S3VectorsRAGIngestion(BaseRAGIngestion, BaseAWSLLM):# Validate bucket name (AWS S3 naming rules)if len(self.vector_bucket_name) < 3:- raise ValueError(+ raise RAGIngestBadRequestError(f"Invalid vector_bucket_name '{self.vector_bucket_name}': "f"AWS S3 bucket names must be at least 3 characters long. "f"Please provide a valid bucket name (e.g., 'my-vector-bucket').")if not self.vector_bucket_name.replace("-", "").replace(".", "").isalnum():- raise ValueError(+ raise RAGIngestBadRequestError(f"Invalid vector_bucket_name '{self.vector_bucket_name}': "f"AWS S3 bucket names can only contain lowercase letters, numbers, hyphens, and periods. "f"Please provide a valid bucket name (e.g., 'my-vector-bucket')."diff --git a/litellm/rag/ingestion/vertex_ai_ingestion.py b/litellm/rag/ingestion/vertex_ai_ingestion.pyindex eff8ad1b8cb..cceddf31117 100644--- a/litellm/rag/ingestion/vertex_ai_ingestion.py+++ b/litellm/rag/ingestion/vertex_ai_ingestion.py@@ -22,7 +22,7 @@ from litellm.llms.custom_httpx.http_handler import ()from litellm.llms.vertex_ai.common_utils import get_vertex_base_urlfrom litellm.llms.vertex_ai.vertex_llm_base import VertexBase-from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion, RAGIngestBadRequestErrorif TYPE_CHECKING:from litellm import Router@@ -134,7 +134,9 @@ class VertexAIRAGIngestion(BaseRAGIngestion, VertexBase):Tuple of (rag_corpus_id, file_id)"""if not self.project_id:- raise ValueError("vertex_project is required for Vertex AI RAG ingestion. Set it in vector_store config.")+ raise RAGIngestBadRequestError(+ "vertex_project is required for Vertex AI RAG ingestion. Set it in vector_store config."+ )# Get or create RAG corpusrag_corpus_id = self.vector_store_config.get("vector_store_id")diff --git a/litellm/types/rag.py b/litellm/types/rag.pyindex 00c070b0996..2f912d21587 100644--- a/litellm/types/rag.py+++ b/litellm/types/rag.py@@ -219,11 +219,12 @@ class RAGIngestOptions(TypedDict, total=False):class RAGIngestResponse(TypedDict, total=False):"""Response from RAG ingest API."""- id: str # Unique ingest job ID- status: Literal["completed", "in_progress", "failed"]- vector_store_id: str # The vector store ID (created or existing)- file_id: str | None # The file ID in the vector store- error: str | None # Error message if status is "failed"+ id: ReadOnly[str] # Unique ingest job ID+ status: ReadOnly[Literal["completed", "in_progress", "failed"]]+ vector_store_id: ReadOnly[str] # The vector store ID (created or existing)+ file_id: ReadOnly[str | None] # The file ID in the vector store+ error: ReadOnly[str | None] # Error message if status is "failed"+ error_status_code: ReadOnly[int | None]class RAGIngestRequest(LiteLLMBaseModel):diff --git a/tests/integration/authorization/test_rag_query_vector_store_allowlist.py b/tests/integration/authorization/test_rag_query_vector_store_allowlist.pyindex 39f0ad1c7e9..f4b5063441f 100644--- a/tests/integration/authorization/test_rag_query_vector_store_allowlist.py+++ b/tests/integration/authorization/test_rag_query_vector_store_allowlist.py@@ -321,6 +321,32 @@ def test_deny_by_default_searches_explicitly_granted_store(strict_gateway: Stricassert marker in str(object_value(searches[0]["body"])["query"]), searches+def test_jwt_team_route_outside_operator_allowed_routes_is_denied_before_search(+ strict_gateway: StrictGateway,+) -> None:+ with strict_gateway.gateway.scenario() as scenario:+ model: Final = scenario.model()+ store_id: Final = f"vs_unregistered_{uuid.uuid4().hex}"+ team: Final = scenario.team(models=_json_array(model), object_permission=_permission_for_stores(store_id))+ member: Final = scenario.member(team)+ marker: Final = f"lit9370 alias {uuid.uuid4().hex}"++ response: Final = _rag_query(+ strict_gateway.gateway,+ model,+ marker,+ strict_gateway.jwt(member, (team,)),+ store_id=store_id,+ path="/rag/query",+ )++ assert response.status_code == 403, response.text+ assert (+ f"Team {team} can access model {model} but route /rag/query is not in litellm_jwtauth.team_allowed_routes"+ ) in response.text, response.text+ assert _searches_for_marker(strict_gateway.upstream, marker, store_id) == ()++@pytest.mark.parametrize(("scope", "error_type"),(("key", "key_vector_store_access_denied"), ("team", "team_vector_store_access_denied")),diff --git a/tests/integration/authorization/test_rag_team_provider_credentials.py b/tests/integration/authorization/test_rag_team_provider_credentials.pynew file mode 100644index 00000000000..8d556b89107--- /dev/null+++ b/tests/integration/authorization/test_rag_team_provider_credentials.py@@ -0,0 +1,2316 @@+from __future__ import annotations++import asyncio+import json+import re+import threading+import time+import uuid+from collections.abc import Callable, Iterable, Iterator, Mapping+from dataclasses import dataclass+from itertools import chain+from pathlib import Path+from queue import SimpleQueue+from types import MappingProxyType+from typing import Final, Literal+from urllib.parse import urlsplit++import anthropic+import httpx+import jwt+import openai+import psutil+import pytest+import yaml+from cryptography.hazmat.primitives.asymmetric import rsa+from integration._support.client import (+ JSON_OBJECT,+ Gateway,+ Scenario,+ eventually,+ gateway_from_environment,+ object_value,+ string_value,+)+from integration._support.database import read_rows+from integration._support.ports import allocate_port+from integration._support.process import graceful_stop_seconds, owned_proxy, owned_proxy_process+from integration._support.wire import Reply, Request, Wire, wire_server+from pydantic import JsonValue++TEAM_API_KEY: Final = "integration-rag-team-key"+WILDCARD_API_KEY: Final = "integration-rag-wildcard-key"+SHARED_API_KEY: Final = "integration-rag-shared-key"+ENVIRONMENT_API_KEY: Final = "integration-rag-environment-key"+CALLER_API_KEY: Final = "integration-rag-caller-key"+FORWARDED_API_KEY: Final = "integration-rag-forwarded-key"+CREDENTIAL_API_KEY: Final = "integration-rag-credential-key"+GEMINI_API_KEY: Final = "integration-rag-gemini-key"+AZURE_API_KEY: Final = "integration-rag-azure-key"+JWT_KEY_ID: Final = "integration-rag-team-provider-jwt"+WILDCARD_MODEL: Final = "openai/gpt-4o-mini"+BARE_WILDCARD_MODEL: Final = "gpt-4o-mini"+OPENAI: Final[Mapping[str, JsonValue]] = MappingProxyType({"custom_llm_provider": "openai"})+DOCUMENT: Final = ("document.txt", b"team provider credentials", "text/plain")+BATCH_INPUT_ROW: Final[Mapping[str, JsonValue]] = MappingProxyType(+ {+ "custom_id": "integration-rag-batch",+ "method": "POST",+ "url": "/v1/chat/completions",+ "body": {"model": BARE_WILDCARD_MODEL, "messages": [{"role": "user", "content": "batch input"}]},+ }+)+BATCH_INPUT: Final = ("batch.jsonl", (json.dumps(dict(BATCH_INPUT_ROW)) + "\n").encode(), "application/jsonl")+FAILING_STORE_NAMES: Final = MappingProxyType({"rag-upstream-401": 401, "rag-upstream-429": 429})+OWNED_PROXY_CELL_SECONDS: Final = 2 * graceful_stop_seconds() + 120+STARTED_WORKER: Final = re.compile(r"Started server process \[(\d+)\]")+PREFIXED: Final = re.compile(r"^/(team|wildcard|shared|environment|credential|caller|gemini|azure|bedrock)(/[^?]*)")+STORE_FILES: Final = re.compile(r"^/v1/vector_stores/([^/]+)/files$")+FILE_CONTENT: Final = re.compile(r"^/v1/files/([^/]+)/content$")+FILE_ITEM: Final = re.compile(r"^/v1/files/([^/]+)$")+BATCH_ITEM: Final = re.compile(r"^/v1/batches/([^/]+)$")+BATCH_CANCEL: Final = re.compile(r"^/v1/batches/([^/]+)/cancel$")+BEDROCK_DATA_SOURCES: Final = re.compile(r"^/knowledgebases/([^/]+)/datasources/$")+BEDROCK_DATA_SOURCE: Final = re.compile(r"^/knowledgebases/([^/]+)/datasources/([^/]+)$")+EMPTY_KNOWLEDGE_BASE: Final = "EMPTYKB000"+BUCKETLESS_KNOWLEDGE_BASE: Final = "NOBUCKET00"+WEB_DATA_SOURCE: Final = "WEBSOURCE0"+STORE_SEARCH: Final = re.compile(r"^(?:/v1|/openai)/vector_stores/([^/]+)/search$")+GEMINI_UPLOAD: Final = re.compile(r"^/upload/v1beta/fileSearchStores/([^:]+):uploadToFileSearchStore$")++JWT_TEAM_COUNT: Final = 10+AWS_AMBIENT_CREDENTIALS: Final = (+ "AWS_PROFILE",+ "AWS_SESSION_TOKEN",+ "AWS_BEARER_TOKEN_BEDROCK",+ "AWS_ROLE_ARN",+ "AWS_ROLE_NAME",+ "AWS_SESSION_NAME",+ "AWS_WEB_IDENTITY_TOKEN_FILE",+)++pytestmark: Final = pytest.mark.timeout(OWNED_PROXY_CELL_SECONDS)++Signature = tuple[str, str, str, str | None]+++@dataclass(frozen=True, slots=True)+class Call:+ prefix: str+ method: str+ route: str+ authorization: str | None+ google_key: str | None+ azure_key: str | None++ @property+ def signature(self) -> Signature:+ return (self.prefix, self.method, self.route, self.authorization)+++@dataclass(frozen=True, slots=True)+class Tenants:+ shared_model: str+ global_model: str+ team_a: str+ team_a_model: str+ team_a_key: str+ restricted_key: str+ viewer_key: str+ jwt_member: str+ team_w: str+ team_w_key: str+ wildcard_bare_key: str+ wildcard_prefixed_key: str+ wildcard_global_key: str+ team_s: str+ team_s_key: str+ teamless_key: str+ jwt_teams: tuple[str, ...]+ jwt_team_model: str+ jwt_multi_member: str+ azure_restricted_key: str+ credential_name: str+ unreachable_credential_name: str+++@dataclass(frozen=True, slots=True)+class RagRig:+ gateway: Gateway+ upstream: Wire+ outage: threading.Event+ tenants: Tenants+ signing_key: rsa.RSAPrivateKey+ scenario: Scenario++ def jwt(self, subject: str, *team_ids: JsonValue) -> str:+ issued_at: Final = int(time.time())+ return jwt.encode(+ {"sub": subject, "groups": list(team_ids), "iat": issued_at, "exp": issued_at + 300},+ self.signing_key,+ algorithm="RS256",+ headers={"kid": JWT_KEY_ID},+ )++ def calls(self) -> tuple[Call, ...]:+ return tuple(_call(request) for request in self.upstream.drain())++ def signatures(self) -> tuple[Signature, ...]:+ return tuple(call.signature for call in self.calls())+++def _call(request: Request) -> Call:+ matched: Final = PREFIXED.match(request.target)+ assert matched is not None, request.target+ return Call(+ prefix=matched[1],+ method=request.method,+ route=matched[2],+ authorization=request.headers.get("authorization"),+ google_key=request.headers.get("x-goog-api-key"),+ azure_key=request.headers.get("api-key"),+ )+++def _json_body(request: Request) -> Mapping[str, JsonValue]:+ if not request.body or not request.headers.get("content-type", "").startswith("application/json"):+ return MappingProxyType({})+ return object_value(json.loads(request.body))+++def _json_reply(payload: Mapping[str, JsonValue], status: int = 200) -> Reply:+ return Reply(status=status, body=json.dumps(payload).encode())+++def _error_reply(status: int) -> Reply:+ return _json_reply(+ {"error": {"message": f"scripted provider {status}", "type": "invalid_request_error", "code": str(status)}},+ status,+ )+++def _vector_store_reply(request: Request, outage: threading.Event) -> Reply:+ if outage.is_set():+ return _error_reply(503)+ name: Final = str(_json_body(request).get("name"))+ failing: Final = FAILING_STORE_NAMES.get(name)+ if failing is not None:+ return _error_reply(failing)+ return _json_reply(+ {+ "id": f"vs_{uuid.uuid4().hex}",+ "object": "vector_store",+ "created_at": int(time.time()),+ "name": name,+ "usage_bytes": 0,+ "status": "completed",+ "file_counts": {"in_progress": 0, "completed": 0, "failed": 0, "cancelled": 0, "total": 0},+ }+ )+++def _owned_by(prefix: str, identity: str) -> bool:+ return identity.startswith((f"file-{prefix}-", f"batch_{prefix}_"))+++def _file_object(identity: str) -> dict[str, JsonValue]:+ return {+ "id": identity,+ "object": "file",+ "bytes": len(DOCUMENT[1]),+ "created_at": int(time.time()),+ "filename": DOCUMENT[0],+ "purpose": "assistants",+ "status": "processed",+ }+++def _file_reply(prefix: str) -> Reply:+ return _json_reply(_file_object(f"file-{prefix}-{uuid.uuid4().hex}"))+++def _batch_input_reply() -> Reply:+ return Reply(status=200, body=BATCH_INPUT[1])+++def _batch_object(identity: str, input_file_id: str, status: str) -> dict[str, JsonValue]:+ return {+ "id": identity,+ "object": "batch",+ "endpoint": "/v1/chat/completions",+ "input_file_id": input_file_id,+ "completion_window": "24h",+ "status": status,+ "created_at": int(time.time()),+ "errors": None,+ "output_file_id": None,+ "error_file_id": None,+ "request_counts": {"total": 0, "completed": 0, "failed": 0},+ "metadata": None,+ }+++def _batch_reply(request: Request, prefix: str) -> Reply:+ body: Final = _json_body(request)+ return _json_reply(+ _batch_object(f"batch_{prefix}_{uuid.uuid4().hex}", str(body.get("input_file_id")), "validating")+ )+++def _list_reply() -> Reply:+ return _json_reply({"object": "list", "data": [], "first_id": None, "last_id": None, "has_more": False})+++def _owned_reply(prefix: str, identity: str, payload: Mapping[str, JsonValue]) -> Reply:+ return _json_reply(payload) if _owned_by(prefix, identity) else _error_reply(404)+++def _openai_get(route: str, prefix: str) -> Reply:+ if route in {"/v1/files", "/v1/batches"}:+ return _list_reply()+ content: Final = FILE_CONTENT.match(route)+ if content is not None:+ return _batch_input_reply() if _owned_by(prefix, content[1]) else _error_reply(404)+ file_item: Final = FILE_ITEM.match(route)+ if file_item is not None:+ return _owned_reply(prefix, file_item[1], _file_object(file_item[1]))+ batch_item: Final = BATCH_ITEM.match(route)+ if batch_item is not None:+ return _owned_reply(prefix, batch_item[1], _batch_object(batch_item[1], f"file-{prefix}-input", "validating"))+ return _error_reply(404)+++def _openai_delete(route: str, prefix: str) -> Reply:+ file_item: Final = FILE_ITEM.match(route)+ if file_item is None:+ return _error_reply(404)+ return _owned_reply(prefix, file_item[1], {"id": file_item[1], "object": "file", "deleted": True})+++def _embedding_reply(request: Request) -> Reply:+ body: Final = _json_body(request)+ inputs: Final = body.get("input")+ count: Final = len(inputs) if isinstance(inputs, list) else 1+ return _json_reply(+ {+ "object": "list",+ "data": [{"object": "embedding", "index": index, "embedding": [0.1, 0.2, 0.3]} for index in range(count)],+ "model": str(body.get("model")),+ "usage": {"prompt_tokens": count, "total_tokens": count},+ }+ )+++def _bedrock_reply(request: Request, route: str) -> Reply:+ listed: Final = BEDROCK_DATA_SOURCES.match(route)+ if request.method == "POST" and listed is not None:+ summary: Final[dict[str, JsonValue]] = {+ "knowledgeBaseId": listed[1],+ "dataSourceId": WEB_DATA_SOURCE,+ "name": "integration-web-source",+ "status": "AVAILABLE",+ "updatedAt": "2026-01-01T00:00:00Z",+ }+ return _json_reply({"dataSourceSummaries": [] if listed[1] == EMPTY_KNOWLEDGE_BASE else [summary]})+ detail: Final = BEDROCK_DATA_SOURCE.match(route)+ if request.method == "GET" and detail is not None:+ return _json_reply(+ {+ "dataSource": {+ "knowledgeBaseId": detail[1],+ "dataSourceId": detail[2],+ "name": "integration-web-source",+ "status": "AVAILABLE",+ "dataSourceConfiguration": {"type": "WEB"},+ "createdAt": "2026-01-01T00:00:00Z",+ "updatedAt": "2026-01-01T00:00:00Z",+ }+ }+ )+ return _error_reply(404)+++def _attach_reply(request: Request, store_id: str) -> Reply:+ return _json_reply(+ {+ "id": str(_json_body(request).get("file_id")),+ "object": "vector_store.file",+ "created_at": int(time.time()),+ "vector_store_id": store_id,+ "status": "completed",+ "last_error": None,+ "usage_bytes": 0,+ }+ )+++def _search_reply(request: Request) -> Reply:+ return _json_reply(+ {+ "object": "vector_store.search_results.page",+ "search_query": _json_body(request).get("query", ""),+ "data": [],+ "has_more": False,+ "next_page": None,+ }+ )+++def _sse(payload: Mapping[str, JsonValue]) -> bytes:+ return f"data: {json.dumps(payload)}\n\n".encode()+++def _chunk(identity: str, model: str, delta: Mapping[str, JsonValue], finish_reason: str | None) -> bytes:+ return _sse(+ {+ "id": identity,+ "object": "chat.completion.chunk",+ "created": int(time.time()),+ "model": model,+ "choices": [{"index": 0, "delta": dict(delta), "finish_reason": finish_reason}],+ }+ )+++def _chat_reply(request: Request) -> Reply:+ body: Final = _json_body(request)+ model: Final = str(body.get("model"))+ identity: Final = f"chatcmpl-{uuid.uuid4().hex}"+ if body.get("stream") is True:+ return Reply(+ content_type="text/event-stream",+ chunks=(+ _chunk(identity, model, {"role": "assistant", "content": "integration response"}, None),+ _chunk(identity, model, {}, "stop"),+ b"data: [DONE]\n\n",+ ),+ )+ return _json_reply(+ {+ "id": identity,+ "object": "chat.completion",+ "created": int(time.time()),+ "model": model,+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "integration response"},+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ }+ )+++def _responses_reply(request: Request) -> Reply:+ identity: Final = uuid.uuid4().hex+ completed: Final = _responses_object(identity, str(_json_body(request).get("model")))+ if _json_body(request).get("stream") is not True:+ return _json_reply(completed)+ events: Final[tuple[tuple[str, Mapping[str, JsonValue]], ...]] = (+ (+ "response.created",+ {+ "type": "response.created",+ "sequence_number": 0,+ "response": {**completed, "status": "in_progress", "output": []},+ },+ ),+ (+ "response.output_text.delta",+ {+ "type": "response.output_text.delta",+ "sequence_number": 1,+ "item_id": f"msg_{identity}",+ "output_index": 0,+ "content_index": 0,+ "delta": "integration response",+ "logprobs": [],+ },+ ),+ ("response.completed", {"type": "response.completed", "sequence_number": 2, "response": completed}),+ )+ return Reply(+ content_type="text/event-stream",+ chunks=tuple(f"event: {name}\ndata: {json.dumps(payload)}\n\n".encode() for name, payload in events),+ )+++def _responses_object(identity: str, model: str) -> dict[str, JsonValue]:+ return {+ "id": f"resp_{identity}",+ "object": "response",+ "created_at": int(time.time()),+ "status": "completed",+ "model": model,+ "output": [+ {+ "type": "message",+ "id": f"msg_{identity}",+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "integration response", "annotations": []}],+ }+ ],+ "parallel_tool_calls": False,+ "tool_choice": "auto",+ "tools": [],+ "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2},+ }+++def _gemini_reply(request: Request, route: str) -> Reply:+ if request.method == "POST" and route == "/v1beta/fileSearchStores":+ return _json_reply({"name": f"fileSearchStores/rag-{uuid.uuid4().hex}"})+ upload: Final = GEMINI_UPLOAD.match(route)+ if request.method == "POST" and upload is not None:+ session_url: Final = f"http://{request.headers['host']}/gemini/upload-session/{upload[1]}"+ return Reply(body=b"{}", headers={"x-goog-upload-url": session_url})+ if request.method == "PUT" and route.startswith("/upload-session/"):+ return _json_reply({"name": f"documents/{uuid.uuid4().hex}"})+ return _error_reply(404)+++def _openai_reply(request: Request, prefix: str, route: str, outage: threading.Event) -> Reply:+ if request.method == "GET":+ return _openai_get(route, prefix)+ if request.method == "DELETE":+ return _openai_delete(route, prefix)+ if request.method != "POST":+ return _error_reply(404)+ if route == "/v1/vector_stores":+ return _vector_store_reply(request, outage)+ if route in {"/v1/files", "/openai/files"}:+ return _file_reply(prefix)+ if route == "/v1/batches":+ return _batch_reply(request, prefix)+ cancelled: Final = BATCH_CANCEL.match(route)+ if cancelled is not None:+ return _owned_reply(prefix, cancelled[1], _batch_object(cancelled[1], f"file-{prefix}-input", "cancelling"))+ if route == "/v1/chat/completions":+ return _chat_reply(request)+ if route == "/v1/responses":+ return _responses_reply(request)+ if route == "/v1/embeddings":+ return _embedding_reply(request)+ attach: Final = STORE_FILES.match(route)+ if attach is not None:+ return _attach_reply(request, attach[1])+ if STORE_SEARCH.match(route) is not None:+ return _search_reply(request)+ return _error_reply(404)+++def _responder(outage: threading.Event) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ matched: Final = PREFIXED.match(request.target)+ if matched is None:+ return _error_reply(404)+ if matched[1] == "gemini":+ return _gemini_reply(request, matched[2])+ if matched[1] == "bedrock":+ return _bedrock_reply(request, matched[2])+ return _openai_reply(request, matched[1], matched[2], outage)++ return respond+++def _proxy_config(directory: Path) -> Path:+ base: Final = object_value(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))+ general_settings: Final = object_value(base["general_settings"])+ config: Final = {+ **base,+ "general_settings": {+ **general_settings,+ "enable_jwt_auth": True,+ "litellm_jwtauth": {"user_id_jwt_field": "sub", "team_ids_jwt_field": "groups"},+ "forward_llm_provider_auth_headers": True,+ },+ "files_settings": [{"custom_llm_provider": "openai"}, {"custom_llm_provider": "azure"}],+ }+ path: Final = directory / "rag_team_provider_credentials.yaml"+ path.write_text(yaml.safe_dump(config))+ return path+++def _provider_environment(upstream: str) -> Mapping[str, str]:+ return MappingProxyType(+ {+ "OPENAI_API_KEY": ENVIRONMENT_API_KEY,+ "OPENAI_API_BASE": f"{upstream}/environment/v1",+ "OPENAI_BASE_URL": f"{upstream}/environment/v1",+ "GEMINI_API_KEY": GEMINI_API_KEY,+ "GEMINI_API_BASE": f"{upstream}/gemini",+ "AZURE_API_KEY": AZURE_API_KEY,+ "AZURE_API_BASE": f"{upstream}/azure",+ "AZURE_API_VERSION": "2025-04-01-preview",+ }+ )+++def _aws_environment(upstream: str) -> Mapping[str, str]:+ return MappingProxyType(+ {+ "AWS_ENDPOINT_URL_BEDROCK_AGENT": f"{upstream}/bedrock",+ "AWS_ACCESS_KEY_ID": "integration-rag-aws-access-key",+ "AWS_SECRET_ACCESS_KEY": "integration-rag-aws-secret-key",+ "AWS_REGION_NAME": "us-east-1",+ "AWS_DEFAULT_REGION": "us-east-1",+ "AWS_EC2_METADATA_DISABLED": "true",+ }+ )+++def _jwt_team_key(team_id: str) -> str:+ return f"integration-rag-jwt-{team_id}"+++def _jwt_team(gateway: Gateway, scenario: Scenario, upstream: str, model: str, member: str) -> str:+ team_id: Final = scenario.team(models=[model])+ _deployment(+ gateway,+ scenario,+ name=model,+ model="openai/gpt-4o-mini",+ api_key=_jwt_team_key(team_id),+ api_base=f"{upstream}/team/v1",+ team_id=team_id,+ )+ gateway.post("/team/member_add", {"team_id": team_id, "member": {"user_id": member, "role": "user"}})+ return team_id+++def _deployment(+ gateway: Gateway,+ scenario: Scenario,+ *,+ name: str,+ model: str,+ api_key: str,+ api_base: str,+ team_id: str | None,+ model_id: str | None = None,+) -> str:+ created: Final = gateway.post(+ "/model/new",+ {+ "model_name": name,+ "litellm_params": {"model": model, "api_key": api_key, "api_base": api_base},+ "model_info": ({} if team_id is None else {"team_id": team_id})+ | ({} if model_id is None else {"id": model_id}),+ },+ )+ model_id: Final = string_value(object_value(created["model_info"])["id"])+ scenario.cleanups.callback(scenario.delete_model, model_id)+ return model_id+++def _delete_credential(gateway: Gateway, name: str) -> None:+ response: Final = gateway.request("DELETE", f"/credentials/{name}")+ assert response.status_code == 200, response.text+++def _credential(gateway: Gateway, scenario: Scenario, api_base: str) -> str:+ name: Final = f"integration-rag-credential-{uuid.uuid4().hex}"+ gateway.post(+ "/credentials",+ {+ "credential_name": name,+ "credential_values": {"api_key": CREDENTIAL_API_KEY, "api_base": api_base},+ "credential_info": {},+ },+ )+ scenario.cleanups.callback(_delete_credential, gateway, name)+ return name+++def _tenants(gateway: Gateway, scenario: Scenario, upstream: str) -> Tenants:+ shared_model: Final = f"integration-rag-shared-{uuid.uuid4().hex}"+ _deployment(+ gateway,+ scenario,+ name=shared_model,+ model="openai/gpt-4o-mini",+ api_key=SHARED_API_KEY,+ api_base=f"{upstream}/shared/v1",+ team_id=None,+ )+ global_model: Final = f"openai/integration-rag-global-{uuid.uuid4().hex}"+ _deployment(+ gateway,+ scenario,+ name=global_model,+ model="openai/gpt-4o-mini",+ api_key=SHARED_API_KEY,+ api_base=f"{upstream}/shared/v1",+ team_id=None,+ )+ team_a_model: Final = f"integration-rag-team-{uuid.uuid4().hex}"+ team_a: Final = scenario.team(models=[team_a_model, shared_model])+ _deployment(+ gateway,+ scenario,+ name=team_a_model,+ model="openai/gpt-4o-mini",+ api_key=TEAM_API_KEY,+ api_base=f"{upstream}/team/v1",+ team_id=team_a,+ )+ viewer: Final = scenario.user(user_role="internal_user_viewer")+ gateway.post("/team/member_add", {"team_id": team_a, "member": {"user_id": viewer, "role": "user"}})+ team_w: Final = scenario.team(models=[shared_model])+ _deployment(+ gateway,+ scenario,+ name="openai/*",+ model="openai/*",+ api_key=WILDCARD_API_KEY,+ api_base=f"{upstream}/wildcard/v1",+ team_id=team_w,+ )+ team_s: Final = scenario.team(models=[shared_model])+ team_z: Final = scenario.team(models=[shared_model])+ _deployment(+ gateway,+ scenario,+ name="azure/*",+ model="azure/*",+ api_key=WILDCARD_API_KEY,+ api_base=f"{upstream}/azure",+ team_id=team_z,+ )+ jwt_team_model: Final = f"integration-rag-jwt-{uuid.uuid4().hex}"+ jwt_multi_member: Final = scenario.user(user_role="internal_user")+ return Tenants(+ shared_model=shared_model,+ global_model=global_model,+ team_a=team_a,+ team_a_model=team_a_model,+ team_a_key=scenario.key(team_id=team_a),+ restricted_key=scenario.key(team_id=team_a, models=[shared_model]),+ viewer_key=scenario.key(user_id=viewer, team_id=team_a),+ jwt_member=scenario.member(team_a),+ team_w=team_w,+ team_w_key=scenario.key(team_id=team_w),+ wildcard_bare_key=scenario.key(team_id=team_w, models=[BARE_WILDCARD_MODEL]),+ wildcard_prefixed_key=scenario.key(team_id=team_w, models=[WILDCARD_MODEL]),+ wildcard_global_key=scenario.key(team_id=team_w, models=[global_model]),+ team_s=team_s,+ team_s_key=scenario.key(team_id=team_s),+ teamless_key=scenario.key(),+ jwt_teams=tuple(+ _jwt_team(gateway, scenario, upstream, jwt_team_model, jwt_multi_member) for _ in range(JWT_TEAM_COUNT)+ ),+ jwt_team_model=jwt_team_model,+ jwt_multi_member=jwt_multi_member,+ azure_restricted_key=scenario.key(team_id=team_z, models=["azure/gpt-4o-mini"]),+ credential_name=_credential(gateway, scenario, f"{upstream}/credential/v1"),+ unreachable_credential_name=_credential(gateway, scenario, _closed_url()),+ )++[email protected](scope="module")+def rag_rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[RagRig]:+ signing_key: Final = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ jwks_body: Final = json.dumps(+ {+ "keys": [+ {+ **json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(signing_key.public_key())),+ "kid": JWT_KEY_ID,+ "use": "sig",+ "alg": "RS256",+ }+ ]+ }+ ).encode()++ def jwks_reply(request: Request) -> Reply:+ assert request.method == "GET", request+ return Reply(body=jwks_body)++ outage: Final = threading.Event()+ directory: Final = tmp_path_factory.mktemp("rag_team_provider_credentials")+ with (+ gateway_from_environment() as admin_gateway,+ admin_gateway.scenario() as scenario,+ wire_server(_responder(outage)) as upstream,+ wire_server(jwks_reply) as jwks,+ ):+ tenants: Final = _tenants(admin_gateway, scenario, upstream.url)+ with (+ owned_proxy(+ admin_gateway,+ directory,+ {+ **_provider_environment(upstream.url),+ **_aws_environment(upstream.url),+ "JWT_PUBLIC_KEY_URL": jwks.url,+ },+ config=_proxy_config(directory),+ remove_environment=("GOOGLE_API_KEY", *AWS_AMBIENT_CREDENTIALS),+ workers=2,+ ) as gateway,+ gateway.scenario() as owned_scenario,+ ):+ yield RagRig(gateway, upstream, outage, tenants, signing_key, owned_scenario)++[email protected](autouse=True)+def _drain_calls_an_earlier_failed_cell_left(request: pytest.FixtureRequest) -> None:+ if "rag_rig" in request.fixturenames:+ request.getfixturevalue("rag_rig").upstream.drain()+++def _ingest_request(name: str, vector_store: Mapping[str, JsonValue]) -> Mapping[str, str]:+ return MappingProxyType(+ {"request": json.dumps({"ingest_options": {"name": name, "vector_store": dict(vector_store)}})}+ )+++def _ingest(+ gateway: Gateway,+ key: str,+ vector_store: Mapping[str, JsonValue] = OPENAI,+ *,+ name: str = "litellm-rag-ingest",+ path: str = "/v1/rag/ingest",+) -> httpx.Response:+ return gateway.request_multipart(path, _ingest_request(name, vector_store), {"file": DOCUMENT}, key=key)+++def _query(+ gateway: Gateway,+ key: str,+ model: str,+ retrieval_config: Mapping[str, JsonValue],+ *,+ stream: bool = False,+ path: str = "/v1/rag/query",+) -> httpx.Response:+ return gateway.request(+ "POST",+ path,+ {+ "model": model,+ "messages": [{"role": "user", "content": f"query team vector store {uuid.uuid4().hex}"}],+ "retrieval_config": {"top_k": 1, **retrieval_config},+ **({"stream": True} if stream else {}),+ },+ key=key,+ )+++def _ingest_signatures(prefix: str, api_key: str, store_id: str) -> tuple[Signature, ...]:+ bearer: Final = f"Bearer {api_key}"+ return (+ (prefix, "POST", "/v1/vector_stores", bearer),+ (prefix, "POST", "/v1/files", bearer),+ (prefix, "POST", f"/v1/vector_stores/{store_id}/files", bearer),+ )+++def _search_signature(prefix: str, api_key: str, store_id: str) -> Signature:+ return (prefix, "POST", f"/v1/vector_stores/{store_id}/search", f"Bearer {api_key}")+++def _chat_signature(prefix: str, api_key: str) -> Signature:+ return (prefix, "POST", "/v1/chat/completions", f"Bearer {api_key}")+++def _completed_store(rig: RagRig, response: httpx.Response) -> str:+ assert response.status_code == 200, response.text+ body: Final = object_value(response.json())+ assert body["status"] == "completed", response.text+ store_id: Final = string_value(body["vector_store_id"])+ rig.scenario.cleanups.callback(rig.gateway.post, "/vector_store/delete", {"vector_store_id": store_id})+ return store_id+++def _store_rows(store_id: str) -> list[dict[str, JsonValue]]:+ return read_rows(+ 'SELECT vector_store_id, team_id, litellm_params, vector_store_metadata FROM "LiteLLM_ManagedVectorStoresTable" '+ "WHERE vector_store_id = %s",+ (store_id,),+ )+++def _closed_url() -> str:+ return f"http://127.0.0.1:{allocate_port()}/v1"+++def test_viewer_ingest_and_team_and_jwt_query_use_team_provider_credentials(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants+ store_id: Final = _completed_store(rag_rig, _ingest(rag_rig.gateway, tenants.viewer_key))+ assert rag_rig.signatures() == _ingest_signatures("team", TEAM_API_KEY, store_id)++ team_query: Final = _query(+ rag_rig.gateway, tenants.team_a_key, tenants.team_a_model, {**OPENAI, "vector_store_id": store_id}+ )+ assert team_query.status_code == 200, team_query.text+ assert rag_rig.signatures() == (+ _search_signature("team", TEAM_API_KEY, store_id),+ _chat_signature("team", TEAM_API_KEY),+ )++ jwt_query: Final = _query(+ rag_rig.gateway,+ rag_rig.jwt(tenants.jwt_member, tenants.team_a),+ tenants.team_a_model,+ {**OPENAI, "vector_store_id": store_id},+ )+ assert jwt_query.status_code == 200, jwt_query.text+ assert rag_rig.signatures() == (+ _search_signature("team", TEAM_API_KEY, store_id),+ _chat_signature("team", TEAM_API_KEY),+ )+++ ("name", "status"), (("rag-upstream-401", 401), ("rag-upstream-429", 429)), ids=("provider_401", "provider_429")+)+def test_failed_ingest_returns_the_provider_status_without_saving_a_store(+ rag_rig: RagRig, name: str, status: int+) -> None:+ before: Final = _store_rows("")++ response: Final = _ingest(rag_rig.gateway, rag_rig.tenants.team_a_key, name=name)++ assert response.status_code == status, response.text+ assert f"scripted provider {status}" in response.text, response.text+ assert rag_rig.signatures() == (("team", "POST", "/v1/vector_stores", f"Bearer {TEAM_API_KEY}"),)+ assert _store_rows("") == before+++def test_unreachable_credential_api_base_fails_ingest_without_saving_a_store(rag_rig: RagRig) -> None:+ before: Final = _store_rows("")++ response: Final = _ingest(+ rag_rig.gateway,+ rag_rig.tenants.team_a_key,+ {**OPENAI, "litellm_credential_name": rag_rig.tenants.unreachable_credential_name},+ )++ assert response.status_code == 500, response.text+ assert rag_rig.calls() == ()+ assert _store_rows("") == before+++def test_rag_alias_ingest_and_query_use_the_team_wildcard_deployment(rag_rig: RagRig) -> None:+ store_id: Final = _completed_store(+ rag_rig, _ingest(rag_rig.gateway, rag_rig.tenants.team_w_key, path="/rag/ingest")+ )+ assert rag_rig.signatures() == _ingest_signatures("wildcard", WILDCARD_API_KEY, store_id)+ rows: Final = _store_rows(store_id)+ assert len(rows) == 1, rows+ assert WILDCARD_API_KEY not in json.dumps(rows), rows++ response: Final = _query(+ rag_rig.gateway,+ rag_rig.tenants.team_w_key,+ WILDCARD_MODEL,+ {**OPENAI, "vector_store_id": store_id},+ path="/rag/query",+ )++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ _search_signature("wildcard", WILDCARD_API_KEY, store_id),+ _chat_signature("wildcard", WILDCARD_API_KEY),+ )+++def test_jwt_team_member_ingest_uses_team_provider_credentials(rag_rig: RagRig) -> None:+ token: Final = rag_rig.jwt(rag_rig.tenants.jwt_member, rag_rig.tenants.team_a)++ store_id: Final = _completed_store(rag_rig, _ingest(rag_rig.gateway, token))++ assert rag_rig.signatures() == _ingest_signatures("team", TEAM_API_KEY, store_id)+ rows: Final = _store_rows(store_id)+ assert [row["team_id"] for row in rows] == [rag_rig.tenants.team_a], rows+++def test_caller_credential_name_wins_over_the_team_deployment(rag_rig: RagRig) -> None:+ store_id: Final = _completed_store(+ rag_rig,+ _ingest(+ rag_rig.gateway,+ rag_rig.tenants.team_a_key,+ {**OPENAI, "litellm_credential_name": rag_rig.tenants.credential_name},+ ),+ )++ assert rag_rig.signatures() == _ingest_signatures("credential", CREDENTIAL_API_KEY, store_id)++[email protected]("field", ("api_key", "api_base"))[email protected]("value", ("set", "null", "empty"))+def test_caller_api_key_or_api_base_on_ingest_is_rejected_before_any_upstream_call(+ rag_rig: RagRig, field: Literal["api_key", "api_base"], value: Literal["set", "null", "empty"]+) -> None:+ set_values: Final = MappingProxyType({"api_key": CALLER_API_KEY, "api_base": f"{rag_rig.upstream.url}/caller/v1"})+ sent: Final[JsonValue] = MappingProxyType({"set": set_values[field], "null": None, "empty": ""})[value]++ response: Final = _ingest(rag_rig.gateway, rag_rig.tenants.team_a_key, {**OPENAI, field: sent})++ assert response.status_code == 400, response.text+ assert f"'{field}' cannot be set in ingest_options.vector_store" in response.text, response.text+ assert rag_rig.calls() == ()++[email protected]("blank", (None, ""), ids=("null", "empty"))+def test_blank_caller_credential_name_falls_back_to_the_team_deployment(rag_rig: RagRig, blank: str | None) -> None:+ tenants: Final = rag_rig.tenants++ store_id: Final = _completed_store(+ rag_rig, _ingest(rag_rig.gateway, tenants.team_a_key, {**OPENAI, "litellm_credential_name": blank})+ )+ assert rag_rig.signatures() == _ingest_signatures("team", TEAM_API_KEY, store_id)++ response: Final = _query(+ rag_rig.gateway, tenants.team_a_key, tenants.team_a_model, {**OPENAI, "vector_store_id": store_id}+ )+ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ _search_signature("team", TEAM_API_KEY, store_id),+ _chat_signature("team", TEAM_API_KEY),+ )++[email protected]("caller", ("teamless_key", "team_s_key", "restricted_key"))+def test_ingest_without_a_usable_team_deployment_uses_the_environment_credentials(+ rag_rig: RagRig, caller: Literal["teamless_key", "team_s_key", "restricted_key"]+) -> None:+ key: Final = getattr(rag_rig.tenants, caller)++ store_id: Final = _completed_store(rag_rig, _ingest(rag_rig.gateway, key))++ assert rag_rig.signatures() == _ingest_signatures("environment", ENVIRONMENT_API_KEY, store_id)+++ ("caller", "prefix", "api_key"),+ (("team_a_key", "team", TEAM_API_KEY), ("team_s_key", "shared", SHARED_API_KEY)),+ ids=("team_deployment", "shared_deployment"),+)+def test_files_upload_keeps_the_accessible_deployment_fallback(+ rag_rig: RagRig, caller: Literal["team_a_key", "team_s_key"], prefix: str, api_key: str+) -> None:+ response: Final = rag_rig.gateway.request_multipart(+ "/v1/files", {"purpose": "assistants"}, {"file": DOCUMENT}, key=getattr(rag_rig.tenants, caller)+ )++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == ((prefix, "POST", "/v1/files", f"Bearer {api_key}"),)+++ ("caller", "model"),+ (("wildcard_bare_key", BARE_WILDCARD_MODEL), ("wildcard_prefixed_key", WILDCARD_MODEL)),+ ids=("bare_model", "prefixed_model"),+)+def test_key_restricted_to_a_model_under_the_team_wildcard_uses_the_team_deployment(+ rag_rig: RagRig, caller: Literal["wildcard_bare_key", "wildcard_prefixed_key"], model: str+) -> None:+ key: Final = getattr(rag_rig.tenants, caller)++ store_id: Final = _completed_store(rag_rig, _ingest(rag_rig.gateway, key))+ assert rag_rig.signatures() == _ingest_signatures("wildcard", WILDCARD_API_KEY, store_id)+ rows: Final = _store_rows(store_id)+ assert [row["team_id"] for row in rows] == [rag_rig.tenants.team_w], rows+ assert WILDCARD_API_KEY not in json.dumps(rows), rows++ response: Final = _query(rag_rig.gateway, key, model, {**OPENAI, "vector_store_id": store_id})++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ _search_signature("wildcard", WILDCARD_API_KEY, store_id),+ _chat_signature("wildcard", WILDCARD_API_KEY),+ )+++def test_key_restricted_to_a_global_model_under_the_team_wildcard_splits_rag_and_chat(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants++ store_id: Final = _completed_store(rag_rig, _ingest(rag_rig.gateway, tenants.wildcard_global_key))+ assert rag_rig.signatures() == _ingest_signatures("wildcard", WILDCARD_API_KEY, store_id)++ response: Final = _query(+ rag_rig.gateway, tenants.wildcard_global_key, tenants.global_model, {**OPENAI, "vector_store_id": store_id}+ )++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ _search_signature("wildcard", WILDCARD_API_KEY, store_id),+ _chat_signature("shared", SHARED_API_KEY),+ )+++def test_files_upload_by_a_key_restricted_under_the_team_wildcard_uses_the_team_deployment(rag_rig: RagRig) -> None:+ response: Final = rag_rig.gateway.request_multipart(+ "/v1/files", {"purpose": "assistants"}, {"file": DOCUMENT}, key=rag_rig.tenants.wildcard_bare_key+ )++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (("wildcard", "POST", "/v1/files", f"Bearer {WILDCARD_API_KEY}"),)++[email protected]("batch_options", ({}, {"litellm_credential_name": "no-such-credential"}), ids=("plain", "credential_name"))+ ("caller", "prefix", "api_key", "reads_input"),+ (("team_a_key", "team", TEAM_API_KEY, False), ("wildcard_bare_key", "wildcard", WILDCARD_API_KEY, True)),+ ids=("team_key", "restricted_wildcard_key"),+)+def test_batch_create_reads_the_input_and_creates_the_batch_through_the_team_deployment(+ rag_rig: RagRig,+ caller: Literal["team_a_key", "wildcard_bare_key"],+ prefix: str,+ api_key: str,+ reads_input: bool,+ batch_options: Mapping[str, JsonValue],+) -> None:+ key: Final = getattr(rag_rig.tenants, caller)+ uploaded: Final = rag_rig.gateway.request_multipart(+ "/v1/files", {"purpose": "batch"}, {"file": BATCH_INPUT}, key=key+ )+ assert uploaded.status_code == 200, uploaded.text+ file_id: Final = string_value(object_value(uploaded.json())["id"])++ created: Final = rag_rig.gateway.request(+ "POST",+ "/v1/batches",+ {"input_file_id": file_id, "endpoint": "/v1/chat/completions", "completion_window": "24h", **batch_options},+ key=key,+ )++ assert created.status_code == 200, created.text+ assert object_value(created.json())["input_file_id"] == file_id, created.text+ bearer: Final = f"Bearer {api_key}"+ input_read: Final = ((prefix, "GET", f"/v1/files/{file_id}/content", bearer),) if reads_input else ()+ assert rag_rig.signatures() == (+ (prefix, "POST", "/v1/files", bearer),+ *input_read,+ (prefix, "POST", "/v1/batches", bearer),+ )+++def test_gemini_ingest_never_receives_the_team_openai_key(rag_rig: RagRig) -> None:+ store_id: Final = _completed_store(+ rag_rig, _ingest(rag_rig.gateway, rag_rig.tenants.team_a_key, {"custom_llm_provider": "gemini"})+ )++ store_name: Final = store_id.removeprefix("fileSearchStores/")+ assert tuple(+ (call.prefix, call.method, call.route, call.google_key, call.authorization) for call in rag_rig.calls()+ ) == (+ ("gemini", "POST", "/v1beta/fileSearchStores", GEMINI_API_KEY, None),+ (+ "gemini",+ "POST",+ f"/upload/v1beta/fileSearchStores/{store_name}:uploadToFileSearchStore",+ GEMINI_API_KEY,+ None,+ ),+ ("gemini", "PUT", f"/upload-session/{store_name}", None, None),+ )++[email protected]("provider", (7, ["openai"], "", "x" * 5120), ids=("int", "list", "empty", "five_kb"))+def test_malformed_ingest_provider_is_rejected_before_any_upstream_call(rag_rig: RagRig, provider: JsonValue) -> None:+ response: Final = _ingest(rag_rig.gateway, rag_rig.tenants.team_a_key, {"custom_llm_provider": provider})++ assert response.status_code == 400, response.text+ assert rag_rig.calls() == ()++[email protected]("stream", (False, True), ids=("json", "stream"))+def test_unmanaged_store_query_searches_with_the_team_deployment(rag_rig: RagRig, stream: bool) -> None:+ tenants: Final = rag_rig.tenants+ store_id: Final = f"vs_unmanaged_{uuid.uuid4().hex}"++ response: Final = _query(+ rag_rig.gateway,+ tenants.team_a_key,+ tenants.team_a_model,+ {**OPENAI, "vector_store_id": store_id},+ stream=stream,+ )++ assert response.status_code == 200, response.text+ assert "integration response" in response.text, response.text+ assert rag_rig.signatures() == (+ _search_signature("team", TEAM_API_KEY, store_id),+ _chat_signature("team", TEAM_API_KEY),+ )++[email protected]("case", ("api_key", "api_base", "null_api_key", "empty_api_key"))+def test_caller_credentials_in_retrieval_config_never_reach_an_unmanaged_search(+ rag_rig: RagRig, case: Literal["api_key", "api_base", "null_api_key", "empty_api_key"]+) -> None:+ tenants: Final = rag_rig.tenants+ store_id: Final = f"vs_unmanaged_{uuid.uuid4().hex}"+ caller_fields: Final[Mapping[str, JsonValue]] = MappingProxyType(+ {+ "api_key": {"api_key": CALLER_API_KEY},+ "api_base": {"api_base": f"{rag_rig.upstream.url}/caller/v1"},+ "null_api_key": {"api_key": None},+ "empty_api_key": {"api_key": ""},+ }[case]+ )++ response: Final = _query(+ rag_rig.gateway,+ tenants.team_a_key,+ tenants.team_a_model,+ {**OPENAI, **caller_fields, "vector_store_id": store_id},+ )++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ _search_signature("team", TEAM_API_KEY, store_id),+ _chat_signature("team", TEAM_API_KEY),+ )+++def _managed_store(rig: RagRig, scenario: Scenario, litellm_params: Mapping[str, JsonValue]) -> str:+ store_id: Final = f"vs_managed_{uuid.uuid4().hex}"+ rig.gateway.post(+ "/vector_store/new",+ {"vector_store_id": store_id, "custom_llm_provider": "openai", "litellm_params": dict(litellm_params)},+ )+ scenario.cleanups.callback(rig.gateway.post, "/vector_store/delete", {"vector_store_id": store_id})+ return store_id+++ ("stored", "prefix", "api_key"),+ (("own_key", "caller", CALLER_API_KEY), ("null_key", "team", TEAM_API_KEY), ("empty_key", "team", TEAM_API_KEY)),+ ids=("own_key", "null_key", "empty_key"),+)+def test_managed_store_credentials_decide_the_search_key(+ rag_rig: RagRig, stored: Literal["own_key", "null_key", "empty_key"], prefix: str, api_key: str+) -> None:+ tenants: Final = rag_rig.tenants+ litellm_params: Final[Mapping[str, JsonValue]] = MappingProxyType(+ {+ "own_key": {"api_key": CALLER_API_KEY, "api_base": f"{rag_rig.upstream.url}/caller/v1"},+ "null_key": {"api_key": None},+ "empty_key": {"api_key": ""},+ }[stored]+ )+ with rag_rig.gateway.scenario() as scenario:+ store_id: Final = _managed_store(rag_rig, scenario, litellm_params)++ response: Final = _query(+ rag_rig.gateway, tenants.team_a_key, tenants.team_a_model, {**OPENAI, "vector_store_id": store_id}+ )++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ _search_signature(prefix, api_key, store_id),+ _chat_signature("team", TEAM_API_KEY),+ )+++def test_credential_name_in_retrieval_config_is_rejected_before_search(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = _query(+ rag_rig.gateway,+ tenants.team_a_key,+ tenants.team_a_model,+ {+ **OPENAI,+ "vector_store_id": f"vs_unmanaged_{uuid.uuid4().hex}",+ "litellm_credential_name": tenants.credential_name,+ },+ )++ assert response.status_code == 400, response.text+ assert rag_rig.calls() == ()+++def test_azure_query_never_receives_the_team_openai_key(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants+ store_id: Final = f"vs_unmanaged_{uuid.uuid4().hex}"++ response: Final = _query(+ rag_rig.gateway,+ tenants.team_a_key,+ tenants.team_a_model,+ {"custom_llm_provider": "azure", "vector_store_id": store_id},+ )++ assert response.status_code == 200, response.text+ assert tuple((call.prefix, call.route, call.azure_key, call.authorization) for call in rag_rig.calls()) == (+ ("azure", f"/openai/vector_stores/{store_id}/search", AZURE_API_KEY, None),+ ("team", "/v1/chat/completions", None, f"Bearer {TEAM_API_KEY}"),+ )+++def test_another_team_cannot_query_a_team_store(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants+ store_id: Final = _completed_store(rag_rig, _ingest(rag_rig.gateway, tenants.team_a_key))+ assert rag_rig.signatures() == _ingest_signatures("team", TEAM_API_KEY, store_id)++ response: Final = _query(+ rag_rig.gateway, tenants.team_w_key, WILDCARD_MODEL, {**OPENAI, "vector_store_id": store_id}+ )++ assert response.status_code == 403, response.text+ assert rag_rig.calls() == ()++[email protected]("vector_store_id", (7, ["vs_a"], None), ids=("int", "list", "null"))+def test_non_string_vector_store_id_is_rejected_before_search(rag_rig: RagRig, vector_store_id: JsonValue) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = _query(+ rag_rig.gateway, tenants.team_a_key, tenants.team_a_model, {**OPENAI, "vector_store_id": vector_store_id}+ )++ assert response.status_code == 400, response.text+ assert "vector_store_id must be a non-empty string" in response.text, response.text+ assert rag_rig.calls() == ()+++def test_empty_vector_store_id_is_rejected_before_search(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = _query(+ rag_rig.gateway, tenants.team_a_key, tenants.team_a_model, {**OPENAI, "vector_store_id": ""}+ )++ assert (response.status_code, rag_rig.signatures()) == (400, ()), response.text+++def test_five_kb_vector_store_id_searches_with_the_team_deployment(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants+ store_id: Final = f"vs_{'v' * 5120}"++ response: Final = _query(+ rag_rig.gateway, tenants.team_a_key, tenants.team_a_model, {**OPENAI, "vector_store_id": store_id}+ )++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ _search_signature("team", TEAM_API_KEY, store_id),+ _chat_signature("team", TEAM_API_KEY),+ )++[email protected]("provider", (7, ["openai"], "", "x" * 5120), ids=("int", "list", "empty", "five_kb"))+def test_malformed_query_provider_fails_without_any_upstream_call(rag_rig: RagRig, provider: JsonValue) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = _query(+ rag_rig.gateway,+ tenants.team_a_key,+ tenants.team_a_model,+ {"custom_llm_provider": provider, "vector_store_id": f"vs_unmanaged_{uuid.uuid4().hex}"},+ )++ assert (response.status_code, rag_rig.signatures()) == (500, ()), response.text+++def test_jwt_route_outside_the_team_allowed_routes_names_the_route(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = rag_rig.gateway.request(+ "POST",+ "/v1beta/interactions",+ {"model": tenants.team_a_model, "input": "hello"},+ key=rag_rig.jwt(tenants.jwt_member, tenants.team_a),+ )++ assert response.status_code == 403, response.text+ assert (+ f"Team {tenants.team_a} can access model {tenants.team_a_model} but route /v1beta/interactions "+ "is not in litellm_jwtauth.team_allowed_routes"+ ) in response.text, response.text+ assert rag_rig.calls() == ()+++def _llm_body(route: str, model: str) -> dict[str, JsonValue]:+ prompt: Final = f"hello {uuid.uuid4().hex}"+ if route == "/v1/responses":+ return {"model": model, "input": prompt}+ if route == "/v1/messages":+ return {"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": prompt}]}+ return {"model": model, "messages": [{"role": "user", "content": prompt}]}++[email protected]("route", ("/v1/chat/completions", "/v1/messages", "/v1/responses"))+def test_jwt_team_member_keeps_its_llm_routes(rag_rig: RagRig, route: str) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = rag_rig.gateway.request(+ "POST",+ route,+ _llm_body(route, tenants.team_a_model),+ key=rag_rig.jwt(tenants.jwt_member, tenants.team_a),+ headers={"anthropic-version": "2023-06-01"},+ )++ assert response.status_code == 200, response.text+ calls: Final = rag_rig.calls()+ assert [(call.prefix, call.authorization) for call in calls] == [("team", f"Bearer {TEAM_API_KEY}")], calls+++async def _ingest_burst(rig: RagRig, names: tuple[str, ...]) -> tuple[httpx.Response, ...]:+ async with httpx.AsyncClient(base_url=str(rig.gateway.client.base_url), timeout=60, trust_env=False) as client:+ return tuple(+ await asyncio.gather(+ *(+ client.post(+ "/v1/rag/ingest",+ data=_ingest_request(name, OPENAI),+ files={"file": DOCUMENT},+ headers={"Authorization": f"Bearer {rig.tenants.team_a_key}"},+ )+ for name in names+ )+ )+ )+++def _burst_names() -> tuple[str, ...]:+ return tuple(f"rag-burst-{uuid.uuid4().hex}" for _ in range(10))+++def _all_ingest_signatures(store_ids: Iterable[str]) -> list[Signature]:+ return sorted(chain.from_iterable(_ingest_signatures("team", TEAM_API_KEY, store_id) for store_id in store_ids))+++async def test_ingest_burst_during_a_provider_outage_fails_each_request_then_recovers(rag_rig: RagRig) -> None:+ before: Final = _store_rows("")+ rag_rig.outage.set()+ try:+ failed: Final = await _ingest_burst(rag_rig, _burst_names())+ finally:+ rag_rig.outage.clear()++ assert [response.status_code for response in failed] == [503] * 10, [response.text for response in failed]+ outage_calls: Final = rag_rig.signatures()+ assert outage_calls == (("team", "POST", "/v1/vector_stores", f"Bearer {TEAM_API_KEY}"),) * 10, outage_calls+ assert _store_rows("") == before++ recovered: Final = await _ingest_burst(rag_rig, _burst_names())++ store_ids: Final = tuple(_completed_store(rag_rig, response) for response in recovered)+ assert len(frozenset(store_ids)) == 10, store_ids+ assert sorted(rag_rig.signatures()) == _all_ingest_signatures(store_ids)+ assert [[row["team_id"] for row in _store_rows(store_id)] for store_id in store_ids] == [+ [rag_rig.tenants.team_a]+ ] * 10+++def _open_upstream_connections(pid: int, upstream: str) -> int:+ port: Final = urlsplit(upstream).port+ return sum(+ 1+ for connection in psutil.Process(pid).net_connections(kind="tcp")+ if connection.status == psutil.CONN_ESTABLISHED and connection.raddr and connection.raddr.port == port+ )+++async def _query_burst(gateway: Gateway, key: str, model: str, count: int) -> tuple[httpx.Response, ...]:+ async with httpx.AsyncClient(base_url=str(gateway.client.base_url), timeout=90, trust_env=False) as client:+ results: Final = await asyncio.gather(+ *(+ client.post(+ "/v1/rag/query",+ json={+ "model": model,+ "messages": [{"role": "user", "content": f"held query {uuid.uuid4().hex}"}],+ "retrieval_config": {**OPENAI, "vector_store_id": f"vs_burst_{uuid.uuid4().hex}", "top_k": 1},+ },+ headers={"Authorization": f"Bearer {key}"},+ )+ for _ in range(count)+ ),+ return_exceptions=True,+ )+ for result in results:+ assert not isinstance(result, BaseException) or isinstance(result, httpx.TransportError), repr(result)+ return tuple(result for result in results if isinstance(result, httpx.Response))+++async def test_worker_sigkill_mid_query_burst_leaves_the_sibling_on_team_credentials(tmp_path: Path) -> None:+ release: Final = threading.Event()+ held_searches: Final[SimpleQueue[str]] = SimpleQueue()++ def respond(request: Request) -> Reply:+ matched: Final = PREFIXED.match(request.target)+ if matched is None:+ return _error_reply(404)+ if STORE_SEARCH.match(matched[2]) is not None:+ held_searches.put(request.target)+ assert release.wait(timeout=60), "The burst was never released"+ return _search_reply(request)+ return _openai_reply(request, matched[1], matched[2], threading.Event())++ with (+ gateway_from_environment() as admin_gateway,+ admin_gateway.scenario() as scenario,+ wire_server(respond) as upstream,+ ):+ model: Final = f"integration-rag-kill-{uuid.uuid4().hex}"+ team_id: Final = scenario.team(models=[model])+ _deployment(+ admin_gateway,+ scenario,+ name=model,+ model="openai/gpt-4o-mini",+ api_key=TEAM_API_KEY,+ api_base=f"{upstream.url}/team/v1",+ team_id=team_id,+ )+ key: Final = scenario.key(team_id=team_id)+ with owned_proxy_process(+ admin_gateway,+ tmp_path,+ _provider_environment(upstream.url),+ remove_environment=("GOOGLE_API_KEY",),+ workers=2,+ ) as owned:+ workers: Final = eventually(+ lambda: tuple(int(pid) for pid in STARTED_WORKER.findall(owned.log.read_text())),+ lambda pids: len(pids) == 2,+ seconds=30,+ )+ burst: Final = asyncio.create_task(_query_burst(owned.gateway, key, model, 20))+ await asyncio.to_thread(eventually, held_searches.qsize, lambda size: size == 20, 60)+ held_by: Final = MappingProxyType({pid: _open_upstream_connections(pid, upstream.url) for pid in workers})+ assert sum(held_by.values()) == 20, held_by+ victim_pid, survivor_pid = sorted(workers, key=held_by.__getitem__)+ with owned.replacing_worker(victim_pid) as kill:+ kill.freeze()+ await asyncio.to_thread(kill)+ release.set()+ served: Final = await burst+ assert held_by[survivor_pid] >= 10, held_by+ assert [response.status_code for response in served] == [200] * held_by[survivor_pid], held_by+ (follow_up,) = await _query_burst(owned.gateway, key, model, 1)+ assert follow_up.status_code == 200, follow_up.text+ calls: Final = tuple(_call(request) for request in upstream.drain())+ assert {(call.prefix, call.authorization) for call in calls} == {("team", f"Bearer {TEAM_API_KEY}")}, calls+ assert sum(1 for call in calls if call.route == "/v1/chat/completions") == held_by[survivor_pid] + 1, calls+++def _ingest_and_drain(+ gateway: Gateway, scenario: Scenario, key: str, upstream: Wire+) -> tuple[str, tuple[Signature, ...]]:+ upstream.drain()+ response: Final = _ingest(gateway, key)+ assert response.status_code == 200, response.text+ store_id: Final = string_value(object_value(response.json())["vector_store_id"])+ scenario.cleanups.callback(gateway.post, "/vector_store/delete", {"vector_store_id": store_id})+ calls: Final = tuple(_call(request) for request in upstream.drain())+ return store_id, tuple(call.signature for call in calls if call.route != "/v1/models")+++def _ingests_after_editing(+ gateway: Gateway, scenario: Scenario, key: str, upstream: Wire, model_id: str+) -> tuple[tuple[str, tuple[Signature, ...]], ...]:+ edited: Final = gateway.request("PATCH", f"/model/{model_id}/update", {"litellm_params": {"timeout": 30}})+ assert edited.status_code == 200, edited.text+ return tuple(_ingest_and_drain(gateway, scenario, key, upstream) for _ in range(4))+++def test_a_team_with_two_openai_deployments_keeps_ingesting_through_the_older_one_after_either_is_edited(+ tmp_path: Path,+) -> None:+ with (+ gateway_from_environment() as admin_gateway,+ admin_gateway.scenario() as scenario,+ wire_server(_responder(threading.Event())) as upstream,+ ):+ team_model: Final = f"integration-rag-team-{uuid.uuid4().hex}"+ wildcard_model: Final = f"integration-rag-wildcard-{uuid.uuid4().hex}"+ team_id: Final = scenario.team(models=[team_model, wildcard_model])+ team_deployment: Final = (+ _deployment(+ admin_gateway,+ scenario,+ name=team_model,+ model="openai/gpt-4o-mini",+ api_key=TEAM_API_KEY,+ api_base=f"{upstream.url}/team/v1",+ team_id=team_id,+ model_id=f"z-{uuid.uuid4().hex}",+ ),+ "team",+ TEAM_API_KEY,+ )+ wildcard_deployment: Final = (+ _deployment(+ admin_gateway,+ scenario,+ name=wildcard_model,+ model="openai/gpt-4o-mini",+ api_key=WILDCARD_API_KEY,+ api_base=f"{upstream.url}/wildcard/v1",+ team_id=team_id,+ model_id=f"a-{uuid.uuid4().hex}",+ ),+ "wildcard",+ WILDCARD_API_KEY,+ )+ (picked_id, picked_prefix, picked_key), (other_id, _, _) = team_deployment, wildcard_deployment+ key: Final = scenario.key(team_id=team_id)+ with (+ owned_proxy(+ admin_gateway,+ tmp_path,+ _provider_environment(upstream.url),+ remove_environment=("GOOGLE_API_KEY",),+ workers=2,+ ) as gateway,+ gateway.scenario() as owned_scenario,+ ):+ ingests: Final = (+ _ingest_and_drain(gateway, owned_scenario, key, upstream),+ *_ingests_after_editing(gateway, owned_scenario, key, upstream, picked_id),+ *_ingests_after_editing(gateway, owned_scenario, key, upstream, other_id),+ )++ assert [calls for _, calls in ingests] == [+ _ingest_signatures(picked_prefix, picked_key, store_id) for store_id, _ in ingests+ ]+++ ("stored", "prefix", "api_key"),+ (("own_key", "caller", CALLER_API_KEY), ("null_key", "team", TEAM_API_KEY)),+ ids=("own_key", "null_key"),+)+def test_ingest_into_a_managed_store_uses_its_own_key_else_the_team_key(+ rag_rig: RagRig, stored: Literal["own_key", "null_key"], prefix: str, api_key: str+) -> None:+ litellm_params: Final[Mapping[str, JsonValue]] = MappingProxyType(+ {+ "own_key": {"api_key": CALLER_API_KEY, "api_base": f"{rag_rig.upstream.url}/caller/v1"},+ "null_key": {"api_key": None},+ }[stored]+ )+ with rag_rig.gateway.scenario() as scenario:+ store_id: Final = _managed_store(rag_rig, scenario, litellm_params)++ response: Final = _ingest(rag_rig.gateway, rag_rig.tenants.team_a_key, {**OPENAI, "vector_store_id": store_id})++ assert response.status_code == 200, response.text+ assert object_value(response.json())["vector_store_id"] == store_id, response.text+ bearer: Final = f"Bearer {api_key}"+ assert rag_rig.signatures() == (+ (prefix, "POST", "/v1/files", bearer),+ (prefix, "POST", f"/v1/vector_stores/{store_id}/files", bearer),+ )+++def _file_id_ingest(gateway: Gateway, key: str, vector_store: Mapping[str, JsonValue]) -> httpx.Response:+ return gateway.request(+ "POST",+ "/v1/rag/ingest",+ {+ "file_id": "file-team-existing",+ "ingest_options": {"name": "litellm-rag-ingest", "vector_store": dict(vector_store)},+ },+ key=key,+ )+++ ("vector_store", "ingestion"),+ (+ ({"custom_llm_provider": "gemini"}, "GeminiRAGIngestion"),+ ({"custom_llm_provider": "bedrock", "vector_store_id": BUCKETLESS_KNOWLEDGE_BASE}, "BedrockRAGIngestion"),+ ({"custom_llm_provider": "s3_vectors", "vector_bucket_name": "integration-bucket"}, "S3VectorsRAGIngestion"),+ ({"custom_llm_provider": "vertex_ai"}, "VertexAIRAGIngestion"),+ ),+ ids=("gemini", "bedrock", "s3_vectors", "vertex_ai"),+)+def test_existing_file_id_on_a_store_that_cannot_take_one_is_rejected_before_any_upstream_call(+ rag_rig: RagRig, vector_store: Mapping[str, JsonValue], ingestion: str+) -> None:+ before: Final = _store_rows("")++ response: Final = _file_id_ingest(rag_rig.gateway, rag_rig.tenants.team_a_key, vector_store)++ assert response.status_code == 400, response.text+ assert f"{ingestion} does not support ingesting an existing file_id" in response.text, response.text+ assert rag_rig.calls() == ()+ assert _store_rows("") == before+++def test_openai_file_id_without_a_vector_store_id_is_rejected_before_any_upstream_call(rag_rig: RagRig) -> None:+ before: Final = _store_rows("")++ response: Final = _file_id_ingest(rag_rig.gateway, rag_rig.tenants.team_a_key, OPENAI)++ assert response.status_code == 400, response.text+ assert "vector_store_id is required when ingesting an existing file_id" in response.text, response.text+ assert rag_rig.calls() == ()+ assert _store_rows("") == before+++def test_openai_file_id_attaches_to_an_existing_store_with_the_team_key(rag_rig: RagRig) -> None:+ store_id: Final = f"vs_existing_{uuid.uuid4().hex}"++ response: Final = _file_id_ingest(+ rag_rig.gateway, rag_rig.tenants.team_a_key, {**OPENAI, "vector_store_id": store_id}+ )++ assert _completed_store(rag_rig, response) == store_id+ assert rag_rig.signatures() == (("team", "POST", f"/v1/vector_stores/{store_id}/files", f"Bearer {TEAM_API_KEY}"),)+++ ("knowledge_base", "error", "routes"),+ (+ (+ EMPTY_KNOWLEDGE_BASE,+ f"No data sources found for Knowledge Base {EMPTY_KNOWLEDGE_BASE}",+ (("POST", f"/knowledgebases/{EMPTY_KNOWLEDGE_BASE}/datasources/"),),+ ),+ (+ BUCKETLESS_KNOWLEDGE_BASE,+ f"Could not auto-detect S3 bucket for data source {WEB_DATA_SOURCE}",+ (+ ("POST", f"/knowledgebases/{BUCKETLESS_KNOWLEDGE_BASE}/datasources/"),+ ("GET", f"/knowledgebases/{BUCKETLESS_KNOWLEDGE_BASE}/datasources/{WEB_DATA_SOURCE}"),+ ),+ ),+ ),+ ids=("no_data_source", "no_s3_bucket"),+)+def test_bedrock_knowledge_base_the_caller_named_without_a_usable_data_source_fails_ingest_with_400(+ rag_rig: RagRig, knowledge_base: str, error: str, routes: tuple[tuple[str, str], ...]+) -> None:+ before: Final = _store_rows("")++ response: Final = _ingest(+ rag_rig.gateway,+ rag_rig.tenants.team_a_key,+ {"custom_llm_provider": "bedrock", "vector_store_id": knowledge_base},+ )++ assert response.status_code == 400, response.text+ assert error in response.text, response.text+ assert tuple((call.prefix, call.method, call.route) for call in rag_rig.calls()) == tuple(+ ("bedrock", method, route) for method, route in routes+ )+ assert _store_rows("") == before+++def test_s3_vectors_bucket_name_the_caller_sent_is_rejected_with_400_after_embedding(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants+ before: Final = _store_rows("")+ request: Final = {+ "request": json.dumps(+ {+ "ingest_options": {+ "name": "litellm-rag-ingest",+ "embedding": {"model": tenants.shared_model},+ "vector_store": {"custom_llm_provider": "s3_vectors", "vector_bucket_name": "ab", "dimension": 3},+ }+ }+ )+ }++ response: Final = rag_rig.gateway.request_multipart(+ "/v1/rag/ingest", request, {"file": DOCUMENT}, key=tenants.team_a_key+ )++ assert response.status_code == 400, response.text+ assert "Invalid vector_bucket_name 'ab'" in response.text, response.text+ assert rag_rig.signatures() == (("shared", "POST", "/v1/embeddings", f"Bearer {SHARED_API_KEY}"),)+ assert _store_rows("") == before+++@dataclass(frozen=True, slots=True)+class KeylessRig:+ gateway: Gateway+ upstream: Wire+ key: str++[email protected](scope="module")+def keyless_rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[KeylessRig]:+ directory: Final = tmp_path_factory.mktemp("rag_keyless_providers")+ with (+ gateway_from_environment() as admin_gateway,+ admin_gateway.scenario() as scenario,+ wire_server(_responder(threading.Event())) as upstream,+ ):+ key: Final = scenario.key()+ with owned_proxy(+ admin_gateway,+ directory,+ {"OPENAI_API_KEY": ENVIRONMENT_API_KEY, "OPENAI_API_BASE": f"{upstream.url}/environment/v1"},+ remove_environment=("GEMINI_API_KEY", "GOOGLE_API_KEY", "VERTEXAI_PROJECT"),+ workers=2,+ ) as gateway:+ yield KeylessRig(gateway, upstream, key)+++ ("provider", "status", "error"),+ (+ ("gemini", 500, "GEMINI_API_KEY or GOOGLE_API_KEY is required for Gemini File Search"),+ ("vertex_ai", 400, "vertex_project is required for Vertex AI RAG ingestion"),+ ),+ ids=("gemini_without_a_proxy_key", "vertex_ai_without_a_project"),+)+def test_ingest_status_says_whether_the_caller_or_the_proxy_must_fix_the_missing_setting(+ keyless_rig: KeylessRig, provider: str, status: int, error: str+) -> None:+ before: Final = _store_rows("")++ response: Final = _ingest(keyless_rig.gateway, keyless_rig.key, {"custom_llm_provider": provider})++ assert response.status_code == status, response.text+ assert error in response.text, response.text+ assert tuple(keyless_rig.upstream.drain()) == ()+ assert _store_rows("") == before+++async def _jwt_chat_burst(rig: RagRig, token: str, model: str, count: int) -> tuple[httpx.Response, ...]:+ async with httpx.AsyncClient(base_url=str(rig.gateway.client.base_url), timeout=60, trust_env=False) as client:+ return tuple(+ await asyncio.gather(+ *(+ client.post(+ "/v1/chat/completions",+ json=_llm_body("/v1/chat/completions", model),+ headers={"Authorization": f"Bearer {token}"},+ )+ for _ in range(count)+ )+ )+ )+++async def test_jwt_in_ten_teams_that_hold_the_model_always_resolves_the_lowest_team_id(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants+ token: Final = rag_rig.jwt(tenants.jwt_multi_member, *reversed(tenants.jwt_teams))++ responses: Final = await _jwt_chat_burst(rag_rig, token, tenants.jwt_team_model, 16)++ assert [response.status_code for response in responses] == [200] * 16, [response.text for response in responses]+ assert (+ rag_rig.signatures()+ == (("team", "POST", "/v1/chat/completions", f"Bearer {_jwt_team_key(min(tenants.jwt_teams))}"),) * 16+ )+++def _prompt() -> str:+ return f"hello {uuid.uuid4().hex}"+++def _sync_sdk_text(route: str, base_url: str, token: str, model: str, stream: bool) -> str:+ if route == "/v1/messages":+ messages_client: Final = anthropic.Anthropic(base_url=base_url, api_key=token, max_retries=0)+ request: Final = {"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": _prompt()}]}+ if stream:+ return "".join(+ event.delta.text+ for event in messages_client.messages.create(**request, stream=True)+ if event.type == "content_block_delta" and event.delta.type == "text_delta"+ )+ message: Final = messages_client.messages.create(**request)+ return "".join(block.text for block in message.content if block.type == "text")+ client: Final = openai.OpenAI(base_url=f"{base_url}/v1", api_key=token, max_retries=0)+ if route == "/v1/responses":+ if stream:+ return "".join(+ event.delta+ for event in client.responses.create(model=model, input=_prompt(), stream=True)+ if event.type == "response.output_text.delta"+ )+ return client.responses.create(model=model, input=_prompt()).output_text+ chat_messages: Final = [{"role": "user", "content": _prompt()}]+ if stream:+ return "".join(+ chunk.choices[0].delta.content or ""+ for chunk in client.chat.completions.create(model=model, messages=chat_messages, stream=True)+ if chunk.choices+ )+ return client.chat.completions.create(model=model, messages=chat_messages).choices[0].message.content or ""+++async def _async_sdk_text(route: str, base_url: str, token: str, model: str, stream: bool) -> str:+ if route == "/v1/messages":+ messages_client: Final = anthropic.AsyncAnthropic(base_url=base_url, api_key=token, max_retries=0)+ request: Final = {"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": _prompt()}]}+ if stream:+ return "".join(+ [+ event.delta.text+ async for event in await messages_client.messages.create(**request, stream=True)+ if event.type == "content_block_delta" and event.delta.type == "text_delta"+ ]+ )+ message: Final = await messages_client.messages.create(**request)+ return "".join(block.text for block in message.content if block.type == "text")+ client: Final = openai.AsyncOpenAI(base_url=f"{base_url}/v1", api_key=token, max_retries=0)+ if route == "/v1/responses":+ if stream:+ return "".join(+ [+ event.delta+ async for event in await client.responses.create(model=model, input=_prompt(), stream=True)+ if event.type == "response.output_text.delta"+ ]+ )+ return (await client.responses.create(model=model, input=_prompt())).output_text+ chat_messages: Final = [{"role": "user", "content": _prompt()}]+ if stream:+ return "".join(+ [+ chunk.choices[0].delta.content or ""+ async for chunk in await client.chat.completions.create(+ model=model, messages=chat_messages, stream=True+ )+ if chunk.choices+ ]+ )+ completion: Final = await client.chat.completions.create(model=model, messages=chat_messages)+ return completion.choices[0].message.content or ""++[email protected]("stream", (False, True), ids=("json", "stream"))[email protected]("client", ("sync", "async"))[email protected]("route", ("/v1/chat/completions", "/v1/messages", "/v1/responses"))+async def test_jwt_team_member_reaches_its_llm_routes_through_the_sdks(+ rag_rig: RagRig, route: str, client: Literal["sync", "async"], stream: bool+) -> None:+ tenants: Final = rag_rig.tenants+ base_url: Final = str(rag_rig.gateway.client.base_url).rstrip("/")+ token: Final = rag_rig.jwt(tenants.jwt_member, tenants.team_a)++ text: Final = (+ await asyncio.to_thread(_sync_sdk_text, route, base_url, token, tenants.team_a_model, stream)+ if client == "sync"+ else await _async_sdk_text(route, base_url, token, tenants.team_a_model, stream)+ )++ assert text == "integration response", text+ calls: Final = rag_rig.calls()+ assert [(call.prefix, call.authorization) for call in calls] == [("team", f"Bearer {TEAM_API_KEY}")], calls+++def _batch_for(rig: RagRig, headers: Mapping[str, str]) -> tuple[str, str]:+ uploaded: Final = rig.gateway.client.post(+ "/v1/files", data={"purpose": "batch"}, files={"file": BATCH_INPUT}, headers=dict(headers)+ )+ assert uploaded.status_code == 200, uploaded.text+ file_id: Final = string_value(object_value(uploaded.json())["id"])+ created: Final = rig.gateway.request(+ "POST",+ "/v1/batches",+ {"input_file_id": file_id, "endpoint": "/v1/chat/completions", "completion_window": "24h"},+ headers=headers,+ )+ assert created.status_code == 200, created.text+ rig.upstream.drain()+ return file_id, string_value(object_value(created.json())["id"])+++FOLLOW_UP_CALLS: Final = (+ ("GET", "/v1/files/{file_id}", "/v1/files/{file_id}"),+ ("GET", "/v1/files/{file_id}/content", "/v1/files/{file_id}/content"),+ ("DELETE", "/v1/files/{file_id}", "/v1/files/{file_id}"),+ ("GET", "/v1/files?purpose=batch&custom_llm_provider=openai", "/v1/files"),+ ("GET", "/v1/batches/{batch_id}", "/v1/batches/{batch_id}"),+ ("POST", "/v1/batches/{batch_id}/cancel", "/v1/batches/{batch_id}/cancel"),+)+FOLLOW_UP_CALL_IDS: Final = (+ "file_retrieve",+ "file_content",+ "file_delete",+ "file_list",+ "batch_retrieve",+ "batch_cancel",+)+++def _bearer(key: str) -> Mapping[str, str]:+ return MappingProxyType({"Authorization": f"Bearer {key}"})++[email protected](("method", "path", "route"), FOLLOW_UP_CALLS, ids=FOLLOW_UP_CALL_IDS)+def test_files_and_batches_calls_by_a_key_restricted_under_the_team_wildcard_use_the_team_deployment(+ rag_rig: RagRig, method: str, path: str, route: str+) -> None:+ key: Final = rag_rig.tenants.wildcard_bare_key+ file_id, batch_id = _batch_for(rag_rig, _bearer(key))++ response: Final = rag_rig.gateway.request(method, path.format(file_id=file_id, batch_id=batch_id), key=key)++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ ("wildcard", method, route.format(file_id=file_id, batch_id=batch_id), f"Bearer {WILDCARD_API_KEY}"),+ )+++def test_batch_list_by_a_key_restricted_under_the_team_wildcard_is_answered_by_the_proxy_without_an_upstream_call(+ rag_rig: RagRig,+) -> None:+ key: Final = rag_rig.tenants.wildcard_bare_key+ _batch_for(rag_rig, _bearer(key))++ response: Final = rag_rig.gateway.request("GET", "/v1/batches?custom_llm_provider=openai", key=key)++ assert response.status_code == 200, response.text+ assert object_value(response.json())["object"] == "list", response.text+ assert rag_rig.signatures() == ()+++def _upload_batch_input(rig: RagRig, key: str) -> str:+ uploaded: Final = rig.gateway.request_multipart("/v1/files", {"purpose": "batch"}, {"file": BATCH_INPUT}, key=key)+ assert uploaded.status_code == 200, uploaded.text+ return string_value(object_value(uploaded.json())["id"])+++def _create_batch(rig: RagRig, key: str, file_id: str) -> httpx.Response:+ return rig.gateway.request(+ "POST",+ "/v1/batches",+ {"input_file_id": file_id, "endpoint": "/v1/chat/completions", "completion_window": "24h"},+ key=key,+ )+++ ("team", "prefix", "api_key"),+ (("team_a", "team", TEAM_API_KEY), ("team_s", "shared", SHARED_API_KEY)),+ ids=("team_deployment", "accessible_deployment"),+)+def test_batch_over_the_key_tpm_limit_is_rejected_after_reading_its_input_where_it_was_uploaded(+ rag_rig: RagRig, team: Literal["team_a", "team_s"], prefix: str, api_key: str+) -> None:+ key: Final = rag_rig.scenario.key(team_id=getattr(rag_rig.tenants, team), tpm_limit=1)+ file_id: Final = _upload_batch_input(rag_rig, key)++ response: Final = _create_batch(rag_rig, key, file_id)++ assert response.status_code == 429, response.text+ bearer: Final = f"Bearer {api_key}"+ assert rag_rig.signatures() == (+ (prefix, "POST", "/v1/files", bearer),+ (prefix, "GET", f"/v1/files/{file_id}/content", bearer),+ )+++def test_batch_whose_input_names_a_model_outside_the_key_allowlist_is_rejected_before_creation(+ rag_rig: RagRig,+) -> None:+ key: Final = rag_rig.tenants.restricted_key+ file_id: Final = _upload_batch_input(rag_rig, key)++ response: Final = _create_batch(rag_rig, key, file_id)++ assert response.status_code == 403, response.text+ assert BARE_WILDCARD_MODEL in response.text, response.text+ bearer: Final = f"Bearer {SHARED_API_KEY}"+ assert rag_rig.signatures() == (+ ("shared", "POST", "/v1/files", bearer),+ ("shared", "GET", f"/v1/files/{file_id}/content", bearer),+ )+++def test_azure_files_upload_by_a_key_restricted_under_the_team_azure_wildcard_uses_the_team_deployment(+ rag_rig: RagRig,+) -> None:+ response: Final = rag_rig.gateway.request_multipart(+ "/v1/files",+ {"purpose": "assistants", "custom_llm_provider": "azure"},+ {"file": DOCUMENT},+ key=rag_rig.tenants.azure_restricted_key,+ )++ assert response.status_code == 200, response.text+ assert tuple((call.prefix, call.method, call.route, call.azure_key) for call in rag_rig.calls()) == (+ ("azure", "POST", "/openai/files", WILDCARD_API_KEY),+ )+++def test_query_without_a_vector_store_id_is_rejected_before_search(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = _query(rag_rig.gateway, tenants.team_a_key, tenants.team_a_model, OPENAI)++ assert response.status_code == 400, response.text+ assert "retrieval_config must contain 'vector_store_id'" in response.text, response.text+ assert rag_rig.calls() == ()+++def _forwarding(key: str) -> Mapping[str, str]:+ return MappingProxyType({"Authorization": f"Bearer {key}", "x-api-key": FORWARDED_API_KEY})+++ ("stored", "stream", "search"),+ (+ (None, False, ("team", FORWARDED_API_KEY)),+ (None, True, ("team", FORWARDED_API_KEY)),+ ("own_key", False, ("caller", CALLER_API_KEY)),+ ("null_key", False, ("team", FORWARDED_API_KEY)),+ ),+ ids=("unmanaged_json", "unmanaged_stream", "managed_own_key", "managed_null_key"),+)+def test_forwarded_provider_key_on_query_wins_over_team_provider_credentials(+ rag_rig: RagRig, stored: Literal["own_key", "null_key"] | None, stream: bool, search: tuple[str, str]+) -> None:+ tenants: Final = rag_rig.tenants+ with rag_rig.gateway.scenario() as scenario:+ store_id: Final = (+ f"vs_unmanaged_{uuid.uuid4().hex}"+ if stored is None+ else _managed_store(+ rag_rig,+ scenario,+ {"api_key": CALLER_API_KEY, "api_base": f"{rag_rig.upstream.url}/caller/v1"}+ if stored == "own_key"+ else {"api_key": None},+ )+ )++ response: Final = rag_rig.gateway.request(+ "POST",+ "/v1/rag/query",+ {+ "model": tenants.team_a_model,+ "messages": [{"role": "user", "content": f"query forwarded key {uuid.uuid4().hex}"}],+ "retrieval_config": {**OPENAI, "top_k": 1, "vector_store_id": store_id},+ **({"stream": True} if stream else {}),+ },+ headers=_forwarding(tenants.team_a_key),+ )++ assert response.status_code == 200, response.text+ assert "integration response" in response.text, response.text+ assert rag_rig.signatures() == (+ _search_signature(search[0], search[1], store_id),+ _chat_signature("team", FORWARDED_API_KEY),+ )+++def test_forwarded_provider_key_on_ingest_wins_over_team_provider_credentials(rag_rig: RagRig) -> None:+ tenants: Final = rag_rig.tenants++ response: Final = rag_rig.gateway.client.post(+ "/v1/rag/ingest",+ data=dict(_ingest_request("litellm-rag-forwarded-key", OPENAI)),+ files={"file": DOCUMENT},+ headers=dict(_forwarding(tenants.team_a_key)),+ )++ store_id: Final = _completed_store(rag_rig, response)+ assert rag_rig.signatures() == _ingest_signatures("team", FORWARDED_API_KEY, store_id)+++ ("caller", "prefix"),+ (("team_a_key", "team"), ("wildcard_bare_key", "wildcard")),+ ids=("team_key", "restricted_wildcard_key"),+)+def test_forwarded_provider_key_on_files_and_batches_wins_over_team_provider_credentials(+ rag_rig: RagRig, caller: Literal["team_a_key", "wildcard_bare_key"], prefix: str+) -> None:+ headers: Final = _forwarding(getattr(rag_rig.tenants, caller))+ uploaded: Final = rag_rig.gateway.client.post(+ "/v1/files", data={"purpose": "batch"}, files={"file": BATCH_INPUT}, headers=dict(headers)+ )+ assert uploaded.status_code == 200, uploaded.text+ file_id: Final = string_value(object_value(uploaded.json())["id"])++ created: Final = rag_rig.gateway.request(+ "POST",+ "/v1/batches",+ {"input_file_id": file_id, "endpoint": "/v1/chat/completions", "completion_window": "24h"},+ headers=headers,+ )++ assert created.status_code == 200, created.text+ calls: Final = rag_rig.calls()+ assert [(call.prefix, call.authorization) for call in calls] == [+ (prefix, f"Bearer {FORWARDED_API_KEY}")+ ] * len(calls), calls+ assert {(call.method, call.route) for call in calls} >= {("POST", "/v1/files"), ("POST", "/v1/batches")}, calls++[email protected]("stray_claim", (7, None), ids=("int", "null"))[email protected]("route", ("/v1/chat/completions", "/v1/rag/query"))+def test_jwt_team_claim_with_a_non_string_entry_still_resolves_the_string_team(+ rag_rig: RagRig, route: str, stray_claim: JsonValue+) -> None:+ tenants: Final = rag_rig.tenants+ token: Final = rag_rig.jwt(tenants.jwt_member, tenants.team_a, stray_claim)+ store_id: Final = f"vs_unmanaged_{uuid.uuid4().hex}"++ response: Final = (+ _query(rag_rig.gateway, token, tenants.team_a_model, {**OPENAI, "vector_store_id": store_id})+ if route == "/v1/rag/query"+ else rag_rig.gateway.request("POST", route, _llm_body(route, tenants.team_a_model), key=token)+ )++ assert response.status_code == 200, response.text+ search: Final = (_search_signature("team", TEAM_API_KEY, store_id),) if route == "/v1/rag/query" else ()+ assert rag_rig.signatures() == (*search, _chat_signature("team", TEAM_API_KEY))++[email protected]("stray_claim", (7, None), ids=("int", "null"))+def test_jwt_header_team_outside_a_claim_with_a_non_string_entry_is_denied_with_403(+ rag_rig: RagRig, stray_claim: JsonValue+) -> None:+ tenants: Final = rag_rig.tenants+ header_team: Final = f"integration-rag-unknown-team-{uuid.uuid4().hex}"++ response: Final = rag_rig.gateway.request(+ "POST",+ "/v1/chat/completions",+ _llm_body("/v1/chat/completions", tenants.team_a_model),+ key=rag_rig.jwt(tenants.jwt_member, tenants.team_a, stray_claim),+ headers={"x-litellm-team-id": header_team},+ )++ assert response.status_code == 403, response.text+ assert f"x-litellm-team-id '{header_team}' does not resolve to a team id or a unique team alias" in response.text, (+ response.text+ )+ assert f"'{tenants.team_a}'" in response.text, response.text+ assert rag_rig.calls() == ()++[email protected](("method", "path", "route"), FOLLOW_UP_CALLS, ids=FOLLOW_UP_CALL_IDS)+ ("caller", "prefix"),+ (("team_a_key", "team"), ("wildcard_bare_key", "wildcard")),+ ids=("team_key", "restricted_wildcard_key"),+)+def test_forwarded_provider_key_on_files_and_batches_follow_up_calls_replaces_the_team_deployment_key(+ rag_rig: RagRig,+ caller: Literal["team_a_key", "wildcard_bare_key"],+ prefix: str,+ method: str,+ path: str,+ route: str,+) -> None:+ headers: Final = _forwarding(getattr(rag_rig.tenants, caller))+ file_id, batch_id = _batch_for(rag_rig, headers)++ response: Final = rag_rig.gateway.request(method, path.format(file_id=file_id, batch_id=batch_id), headers=headers)++ assert response.status_code == 200, response.text+ assert rag_rig.signatures() == (+ (prefix, method, route.format(file_id=file_id, batch_id=batch_id), f"Bearer {FORWARDED_API_KEY}"),+ )+++ ("x_api_key", "prefix", "api_key"),+ (+ (("",), "wildcard", WILDCARD_API_KEY),+ (("f" * 5120,), "wildcard", "f" * 5120),+ ((FORWARDED_API_KEY, FORWARDED_API_KEY), "wildcard", FORWARDED_API_KEY),+ ),+ ids=("empty", "five_kb", "repeated"),+)+def test_blank_oversized_or_repeated_forwarded_provider_key_on_files_and_batches(+ rag_rig: RagRig, x_api_key: tuple[str, ...], prefix: str, api_key: str+) -> None:+ headers: Final = (+ ("Authorization", f"Bearer {rag_rig.tenants.wildcard_bare_key}"),+ *(("x-api-key", value) for value in x_api_key),+ )+ uploaded: Final = rag_rig.gateway.client.post(+ "/v1/files", data={"purpose": "batch"}, files={"file": BATCH_INPUT}, headers=headers+ )+ assert uploaded.status_code == 200, uploaded.text+ file_id: Final = string_value(JSON_OBJECT.validate_json(uploaded.content)["id"])++ created: Final = rag_rig.gateway.client.post(+ "/v1/batches",+ json={"input_file_id": file_id, "endpoint": "/v1/chat/completions", "completion_window": "24h"},+ headers=headers,+ )++ assert created.status_code == 200, created.text+ calls: Final = rag_rig.calls()+ assert [(call.prefix, call.authorization) for call in calls] == [(prefix, f"Bearer {api_key}")] * len(calls), calls+ assert {(call.method, call.route) for call in calls} == {+ ("POST", "/v1/files"),+ ("GET", f"/v1/files/{file_id}/content"),+ ("POST", "/v1/batches"),+ }, calls+++def _forwarded_ingest(rig: RagRig, vector_store: Mapping[str, JsonValue]) -> httpx.Response:+ return rig.gateway.client.post(+ "/v1/rag/ingest",+ data=dict(_ingest_request("litellm-rag-forwarded-key", vector_store)),+ files={"file": DOCUMENT},+ headers=dict(_forwarding(rig.tenants.team_a_key)),+ )+++def test_forwarded_provider_key_on_ingest_never_overrides_a_named_credential(rag_rig: RagRig) -> None:+ store_id: Final = _completed_store(+ rag_rig, _forwarded_ingest(rag_rig, {**OPENAI, "litellm_credential_name": rag_rig.tenants.credential_name})+ )++ assert rag_rig.signatures() == _ingest_signatures("credential", CREDENTIAL_API_KEY, store_id)+++ ("stored", "prefix", "api_key"),+ (("own_key", "caller", CALLER_API_KEY), ("null_key", "team", FORWARDED_API_KEY)),+ ids=("own_key", "null_key"),+)+def test_forwarded_provider_key_on_ingest_into_a_managed_store_yields_only_to_the_store_key(+ rag_rig: RagRig, stored: Literal["own_key", "null_key"], prefix: str, api_key: str+) -> None:+ with rag_rig.gateway.scenario() as scenario:+ store_id: Final = _managed_store(+ rag_rig,+ scenario,+ {"api_key": CALLER_API_KEY, "api_base": f"{rag_rig.upstream.url}/caller/v1"}+ if stored == "own_key"+ else {"api_key": None},+ )++ response: Final = _forwarded_ingest(rag_rig, {**OPENAI, "vector_store_id": store_id})++ assert response.status_code == 200, response.text+ assert JSON_OBJECT.validate_json(response.content)["vector_store_id"] == store_id, response.text+ bearer: Final = f"Bearer {api_key}"+ assert rag_rig.signatures() == (+ (prefix, "POST", "/v1/files", bearer),+ (prefix, "POST", f"/v1/vector_stores/{store_id}/files", bearer),+ )+++def test_forwarded_provider_key_never_reaches_a_gemini_ingest(rag_rig: RagRig) -> None:+ store_id: Final = _completed_store(rag_rig, _forwarded_ingest(rag_rig, {"custom_llm_provider": "gemini"}))++ requests: Final = rag_rig.upstream.drain()+ store_name: Final = store_id.removeprefix("fileSearchStores/")+ assert tuple(+ (call.prefix, call.method, call.route, call.google_key, call.authorization)+ for call in (_call(request) for request in requests)+ ) == (+ ("gemini", "POST", "/v1beta/fileSearchStores", GEMINI_API_KEY, None),+ (+ "gemini",+ "POST",+ f"/upload/v1beta/fileSearchStores/{store_name}:uploadToFileSearchStore",+ GEMINI_API_KEY,+ None,+ ),+ ("gemini", "PUT", f"/upload-session/{store_name}", None, None),+ )+ assert [request.headers.get("x-api-key") for request in requests] == [None] * len(requests), requestsdiff --git a/tests/unit/proxy/auth/test_handle_jwt.py b/tests/unit/proxy/auth/test_handle_jwt.pyindex e4a3935a58d..a0ea6ce0403 100644--- a/tests/unit/proxy/auth/test_handle_jwt.py+++ b/tests/unit/proxy/auth/test_handle_jwt.py@@ -1,7 +1,9 @@import asyncioimport re+import sysimport timefrom collections.abc import Mapping, Sequence+from types import ModuleTypefrom typing import Finalfrom unittest.mock import AsyncMock, MagicMock, patch@@ -296,6 +298,84 @@ async def test_find_team_with_model_access_uses_request_method_for_passthrough_aassert "allowed_passthrough_routes" in exc_info.value.detail++class _TeamClaims(set[str]):+ def __init__(self, claim_order: tuple[str, ...]):+ super().__init__(claim_order)+ self.claim_order = claim_order++ def __iter__(self):+ return iter(self.claim_order)++[email protected]("claim_order", [("team-a", "team-b"), ("team-b", "team-a")])+async def test_a_jwt_in_two_teams_resolves_the_same_team_in_any_claim_order(claim_order: tuple[str, ...]):+ jwt_handler = JWTHandler()+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth()+ teams = {team_id: LiteLLM_TeamTable(team_id=team_id, models=["gpt-4"], metadata={}) for team_id in claim_order}++ with (+ patch(+ "litellm.proxy.auth.handle_jwt.get_team_object",+ new_callable=AsyncMock,+ side_effect=lambda team_id, **_: teams[team_id],+ ),+ patch(+ "litellm.proxy.auth.handle_jwt.can_team_access_model",+ new_callable=AsyncMock,+ return_value=True,+ ),+ ):+ team_id, team_obj = await JWTAuthManager.find_team_with_model_access(+ team_ids=_TeamClaims(claim_order),+ requested_model="gpt-4",+ route="/v1/rag/query",+ jwt_handler=jwt_handler,+ prisma_client=None,+ user_api_key_cache=MagicMock(),+ parent_otel_span=None,+ proxy_logging_obj=MagicMock(),+ )++ assert team_id == "team-a"+ assert team_obj == teams["team-a"]++[email protected]("stray_claim", [1, None])+async def test_a_jwt_team_claim_with_a_non_string_entry_still_resolves_the_string_team(stray_claim: object):+ jwt_handler: Final = JWTHandler()+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_ids_jwt_field="groups")+ team: Final = LiteLLM_TeamTable(team_id="aa-team", models=["gpt-4"], metadata={})++ with (+ patch(+ "litellm.proxy.auth.handle_jwt.get_team_object",+ new_callable=AsyncMock,+ side_effect=lambda team_id, **_: {"aa-team": team}[team_id],+ ),+ patch(+ "litellm.proxy.auth.handle_jwt.can_team_access_model",+ new_callable=AsyncMock,+ return_value=True,+ ),+ ):+ team_id, team_obj = await JWTAuthManager.find_team_with_model_access(+ team_ids=set(jwt_handler.get_team_ids_from_jwt({"groups": ["aa-team", stray_claim]})),+ requested_model="gpt-4",+ route="/chat/completions",+ jwt_handler=jwt_handler,+ prisma_client=None,+ user_api_key_cache=MagicMock(),+ parent_otel_span=None,+ proxy_logging_obj=MagicMock(),+ )++ assert team_id == "aa-team"+ assert team_obj == team++_AUTH_ENFORCED_MODEL_HOST_ROUTES: Final = {"test-uuid-1:subpath:/model-host/v1/extractor:GET,POST": {"endpoint_id": "test-uuid-1",@@ -1483,8 +1563,13 @@ async def test_find_team_with_model_access_v1_messages_default_routes(monkeypatc[("/v1/messages", True),("/v1/messages/count_tokens", True),+ ("/rag/ingest", True),+ ("/v1/rag/ingest", True),+ ("/rag/query", True),+ ("/v1/rag/query", True),("/v1/skills", False),("/v1/skills/skill_abc123", False),+ ("/lens", False),],)def test_default_team_allowed_routes_cover_messages_but_not_skills(route, expected):@@ -1500,6 +1585,40 @@ def test_default_team_allowed_routes_cover_messages_but_not_skills(route, expect)+async def test_find_team_with_model_access_reports_team_route_allowlist_denial():+ jwt_handler: Final = JWTHandler()+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_allowed_routes=["/chat/completions"])+ team: Final = LiteLLM_TeamTable(team_id="team-route-denied", models=["gpt-4o-mini"])+ user_api_key_cache: Final = DualCache()+ user_api_key_cache.set_cache(key="team_id:team-route-denied", value=team)+ prisma_client: Final = MagicMock()+ prisma_team_table: Final = prisma_client.db.litellm_teamtable+ prisma_team_table.find_unique = AsyncMock()+ proxy_server_module: Final = ModuleType("proxy_server")+ proxy_server_module.llm_router = None++ with patch.dict(sys.modules, {"litellm.proxy.proxy_server": proxy_server_module}):+ with pytest.raises(HTTPException) as exc_info:+ await JWTAuthManager.find_team_with_model_access(+ team_ids={"team-route-denied"},+ requested_model="gpt-4o-mini",+ route="/rag/query",+ jwt_handler=jwt_handler,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=None,+ proxy_logging_obj=MagicMock(),+ )++ prisma_team_table.find_unique.assert_not_awaited()+ assert exc_info.value.status_code == 403+ assert (+ exc_info.value.detail == "Team team-route-denied can access model gpt-4o-mini but route /rag/query "+ "is not in litellm_jwtauth.team_allowed_routes"+ )++@pytest.mark.asyncioasync def test_auth_builder_returns_team_membership_object():"""@@ -7011,6 +7130,23 @@ async def test_resolve_team_from_header_denies_aliases_of_teams_the_jwt_does_not)[email protected]("stray_claim", [1, None])+async def test_resolve_team_from_header_denies_an_unknown_team_with_403_when_the_jwt_claim_holds_a_non_string(+ stray_claim: object,+):+ jwt_handler: Final = JWTHandler()+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_ids_jwt_field="groups")+ allowed_team_ids: Final = set(jwt_handler.get_team_ids_from_jwt({"groups": ["team_a", stray_claim]}))++ with pytest.raises(HTTPException) as denied:+ await _resolve_header("no_such", allowed_team_ids, False, _team_lookup_404, _teams_by_alias({}))++ assert denied.value.status_code == 403+ assert "'no_such' does not resolve" in denied.value.detail+ assert "'team_a'" in denied.value.detail++@pytest.mark.asyncioasync def test_resolve_team_from_header_under_db_fallback_tries_the_id_before_the_alias():"""Under fallback_to_db_teams a claimless JWT's header is provisional: a valuediff --git a/tests/unit/proxy/batches_endpoints/test_endpoints.py b/tests/unit/proxy/batches_endpoints/test_endpoints.pyindex 15a254dd7a1..9ef35444419 100644--- a/tests/unit/proxy/batches_endpoints/test_endpoints.py+++ b/tests/unit/proxy/batches_endpoints/test_endpoints.py@@ -36,7 +36,7 @@ from contextlib import ExitStackfrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom pathlib import Path-from typing import Any, Dict, Optional+from typing import Any, Dict, Final, Optionalfrom unittest.mock import AsyncMock, MagicMock, patchimport httpx@@ -59,6 +59,7 @@ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfofrom litellm.types.utils import CredentialItem, LiteLLMBatch, SpecialEnumsfrom fastapi import HTTPException, Request, Response+from starlette.datastructures import Headers, QueryParams# --------------------------------------------------------------------------- ## Fixtures: distinguishable credentials per model so a wrong/hardcoded model_id@@ -124,8 +125,8 @@ class FakeRequest:headers: Optional[Dict[str, str]] = None,query: Optional[Dict[str, str]] = None,):- self.headers = headers or {}- self.query_params = query or {}+ self.headers = Headers(headers=headers or {})+ self.query_params = QueryParams(query or {})@pytest.fixture@@ -937,6 +938,42 @@ async def test_create__raw_file_with_executed_model_400_with_upload_guidance(harharness.router_acreate.assert_not_called()+async def _create_with_model_headers(harness: Harness, *models: str):+ harness.upstream_files_route.mock(return_value=httpx.Response(200, json={"object": "list", "data": []}))+ set_body(harness, {"input_file_id": "file-plain", "endpoint": "/v1/chat/completions", "completion_window": "24h"})+ request: Final = Request(+ {+ "type": "http",+ "method": "POST",+ "path": "/v1/batches",+ "query_string": b"",+ "headers": [(b"x-litellm-model", model.encode()) for model in models],+ }+ )+ return await endpoints.create_batch(+ request=request, fastapi_response=Response(), provider=None, user_api_key_dict=UserAPIKeyAuth(api_key="sk-test")+ )+++async def test_create__model_headers_naming_different_models_are_rejected_before_anything_runs(harness):+ with pytest.raises(ProxyException) as exc:+ await _create_with_model_headers(harness, "vertex-model", "my-vllm")++ assert exc.value.code == "400"+ assert "x-litellm-model" in exc.value.message+ harness.pre_call.assert_not_called()+ harness.litellm_acreate.assert_not_called()+ harness.router_acreate.assert_not_called()+++async def test_create__the_same_model_header_twice_still_routes_to_that_model(harness):+ await _create_with_model_headers(harness, "my-vllm", "my-vllm")++ assert harness.acreate_kwargs()["api_base"] == CREDS["my-vllm"]["api_base"]++@pytest.mark.asyncio@pytest.mark.parametrize("upstream_answer",@@ -1059,8 +1096,8 @@ def _raw_batches_request(body: Dict[str, Any]) -> MagicMock:request.url.path = "/v1/batches"request.method = "POST"request.scope = {"type": "http", "method": "POST", "path": "/v1/batches"}- request.query_params = {}- request.headers = {"Content-Type": "application/json"}+ request.query_params = QueryParams({})+ request.headers = Headers(headers={"Content-Type": "application/json"})request.client = MagicMock()request.client.host = "127.0.0.1"request.body = AsyncMock(return_value=json.dumps(body).encode())diff --git a/tests/unit/proxy/hooks/test_batch_rate_limiter.py b/tests/unit/proxy/hooks/test_batch_rate_limiter.pyindex b4e972ea34f..b10cd9e7107 100644--- a/tests/unit/proxy/hooks/test_batch_rate_limiter.py+++ b/tests/unit/proxy/hooks/test_batch_rate_limiter.py@@ -8,7 +8,7 @@ are charged against a 24h token window instead of their minute counters.import jsonimport time-from collections.abc import Iterator, Sequence+from collections.abc import Callable, Iterator, Sequencefrom datetime import datetime, timezonefrom typing import Final, Literalfrom unittest.mock import AsyncMock, MagicMock@@ -482,6 +482,155 @@ async def test_batch_rate_limiter_without_user_context(openai_files: respx.MockRassert usage_without_context.total_tokens == usage_with_context.total_tokens == _token_counter_total(rows)+async def test_batch_input_without_a_model_is_read_through_the_team_deployment(+ openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ from litellm import Router+ from litellm.proxy import proxy_server++ monkeypatch.setattr(+ proxy_server,+ "llm_router",+ Router(+ model_list=[+ {+ "model_name": "openai/*",+ "litellm_params": {+ "model": "openai/*",+ "api_key": "sk-team",+ "api_base": "https://team.example/v1",+ },+ "model_info": {"id": "team-openai", "team_id": "team-1"},+ }+ ]+ ),+ )+ _, _, batch_limiter = _make_limiters()+ rows: Final = _batch_rows(("Hello",))+ environment_route: Final = _serve_file(openai_files, "file-abc123", rows)+ team_route: Final = openai_files.get("https://team.example/v1/files/file-abc123/content").mock(+ return_value=httpx.Response(200, content="\n".join(json.dumps(row) for row in rows).encode())+ )+ team_key: Final = UserAPIKeyAuth(api_key="sk", team_id="team-1", team_models=["openai/*"], models=[_BATCH_MODEL])+ teamless_key: Final = UserAPIKeyAuth(api_key="sk")++ team_usage: Final = await batch_limiter.count_input_file_usage(+ file_id="file-abc123", custom_llm_provider="openai", user_api_key_dict=team_key, data={}+ )+ teamless_usage: Final = await batch_limiter.count_input_file_usage(+ file_id="file-abc123", custom_llm_provider="openai", user_api_key_dict=teamless_key, data={}+ )++ assert team_route.call_count == 1+ assert team_route.calls.last.request.headers["authorization"] == "Bearer sk-team"+ assert environment_route.call_count == 1+ assert environment_route.calls.last.request.headers["authorization"] == "Bearer sk-test"+ assert team_usage.total_tokens == teamless_usage.total_tokens == _token_counter_total(rows)++ forwarded_usage: Final = await batch_limiter.count_input_file_usage(+ file_id="file-abc123",+ custom_llm_provider="openai",+ user_api_key_dict=team_key,+ data={"api_key": "sk-forwarded"},+ )++ assert team_route.call_count == 2+ assert team_route.calls.last.request.headers["authorization"] == "Bearer sk-forwarded"+ assert environment_route.call_count == 1+ assert forwarded_usage.total_tokens == _token_counter_total(rows)+++_ROUTED_FILE_URL: Final = "https://routed.example/v1/files/file-abc123/content"+++def _serve_file_to_the_deployment_key(rows: Sequence[_BatchLine]) -> Callable[[httpx.Request], httpx.Response]:+ jsonl: Final = "\n".join(json.dumps(row) for row in rows).encode()++ def respond(request: httpx.Request) -> httpx.Response:+ if request.headers.get("authorization") != "Bearer sk-deployment":+ return httpx.Response(401, json={"error": {"message": "Incorrect API key provided"}})+ return httpx.Response(200, content=jsonl)++ return respond+++ "query_string, routing_headers",+ [(b"model=routed-batch-model", ()), (b"", ((b"x-litellm-model", b"routed-batch-model"),))],+ ids=["query", "header"],+)+async def test_model_routed_batch_is_counted_with_the_deployment_key_not_the_request_key(+ openai_files: respx.MockRouter,+ monkeypatch: pytest.MonkeyPatch,+ query_string: bytes,+ routing_headers: tuple[tuple[bytes, bytes], ...],+):+ from starlette.requests import Request++ from litellm import Router+ from litellm.proxy import proxy_server+ from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request++ monkeypatch.setattr(+ proxy_server,+ "llm_router",+ Router(+ model_list=[+ {+ "model_name": "routed-batch-model",+ "litellm_params": {+ "model": f"openai/{_BATCH_MODEL}",+ "api_key": "sk-deployment",+ "api_base": "https://routed.example/v1",+ },+ "model_info": {"id": "routed-batch-deployment"},+ }+ ]+ ),+ )+ file_route: Final = openai_files.get(_ROUTED_FILE_URL).mock(+ side_effect=_serve_file_to_the_deployment_key(_batch_rows(("Hello " * 50,)))+ )+ user_api_key_dict: Final = UserAPIKeyAuth(api_key=hash_token("sk-batch"), tpm_limit=1)+ request: Final = Request(+ {+ "type": "http",+ "method": "POST",+ "path": "/v1/batches",+ "raw_path": b"/v1/batches",+ "root_path": "",+ "scheme": "http",+ "server": ("proxy.test", 80),+ "client": ("127.0.0.1", 50000),+ "query_string": query_string,+ "headers": [(b"content-type", b"application/json"), *routing_headers],+ }+ )+ data: Final = await add_litellm_data_to_request(+ data={+ "input_file_id": "file-abc123",+ "endpoint": "/v1/chat/completions",+ "completion_window": "24h",+ "api_key": "sk-not-the-deployment-key",+ },+ request=request,+ user_api_key_dict=user_api_key_dict,+ proxy_config=MagicMock(),+ general_settings={},+ )+ _, _, batch_limiter = _make_limiters()++ with pytest.raises(HTTPException) as exc:+ await batch_limiter.async_pre_call_hook(+ user_api_key_dict=user_api_key_dict, cache=DualCache(), data=data, call_type="acreate_batch"+ )++ assert exc.value.status_code == 429+ assert file_route.call_count == 1++async def _install_managed_file_hook(openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, rows: str) -> tuple[respx.Route, respx.Route]:diff --git a/tests/unit/proxy/openai_files_endpoint/test_files_common_utils.py b/tests/unit/proxy/openai_files_endpoint/test_files_common_utils.pyindex 180ece77a6e..f6c6b51fc93 100644--- a/tests/unit/proxy/openai_files_endpoint/test_files_common_utils.py+++ b/tests/unit/proxy/openai_files_endpoint/test_files_common_utils.py@@ -1,14 +1,20 @@+from datetime import datetime, timezonefrom types import MappingProxyTypefrom typing import Finalfrom unittest.mock import AsyncMock, MagicMockimport pytest+from fastapi import HTTPExceptionfrom litellm_enterprise.proxy.hooks.managed_files import _PROXY_LiteLLMManagedFiles+from litellm import Routerfrom litellm.caching.caching import DualCache+from litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.openai_files_endpoints.common_utils import (+ apply_team_provider_credentials,apply_unified_file_ids,get_credentials_for_model,+ get_team_provider_credentials,is_litellm_executed_batch,map_raw_file_ids_to_unified,)@@ -461,9 +467,7 @@ from litellm.proxy.openai_files_endpoints.common_utils import ()-def _completed_batch_for_retire(- output_file_id: str | None, counts: BatchRequestCounts | None = None-) -> LiteLLMBatch:+def _completed_batch_for_retire(output_file_id: str | None, counts: BatchRequestCounts | None = None) -> LiteLLMBatch:kwargs = dict(id="batch-1",completion_window="24h",@@ -652,3 +656,198 @@ async def test_batch_cancel_updates_database(caplog: pytest.LogCaptureFixture):assert "batch_processed" not in writtenassert json.loads(written["file_object"])["cancelled_at"] == 1234567999assert f"Updating batch {batch_id} status to cancelled after cancel" in caplog.messages+++def _team_openai_router(team_public_model_name: str, deployment_model: str) -> Router:+ return Router(+ model_list=[+ {+ "model_name": team_public_model_name,+ "litellm_params": {"model": deployment_model, "api_key": "team-openai-key"},+ "model_info": {+ "id": "team-a-openai",+ "team_id": "team-a",+ "team_public_model_name": team_public_model_name,+ },+ },+ {+ "model_name": "claude-opus-4-6",+ "litellm_params": {"model": "anthropic/claude-opus-4-6", "api_key": "anthropic-key"},+ },+ ]+ )+++def _team_only_openai_credentials(+ team_public_model_name: str, deployment_model: str, key_models: list[str]+) -> dict | None:+ return get_team_provider_credentials(+ llm_router=_team_openai_router(team_public_model_name, deployment_model),+ user_api_key_dict=UserAPIKeyAuth(+ api_key="test-key",+ user_id="test-user",+ team_id="team-a",+ team_models=[team_public_model_name, "claude-opus-4-6"],+ models=key_models,+ ),+ custom_llm_provider="openai",+ include_accessible_deployments=False,+ )+++ "team_public_model_name, deployment_model, key_models",+ [+ ("openai/*", "openai/*", ["gpt-4o"]),+ ("openai/*", "openai/*", ["openai/gpt-4o"]),+ ("gpt-4o", "openai/gpt-4o", ["openai/*"]),+ ],+)+def test_a_restricted_key_resolves_the_team_deployment_its_wildcard_or_model_covers(+ team_public_model_name: str, deployment_model: str, key_models: list[str]+):+ credentials = _team_only_openai_credentials(team_public_model_name, deployment_model, key_models)++ assert credentials is not None+ assert credentials["api_key"] == "team-openai-key"++[email protected]("key_models", [["claude-opus-4-6"], ["anthropic/*"]])+def test_a_restricted_key_outside_the_team_wildcard_never_resolves_its_credentials(key_models: list[str]):+ assert _team_only_openai_credentials("openai/*", "openai/*", key_models) is None+++ "request_credentials, sent_api_key, sent_api_base",+ [+ ({}, "team-openai-key", "https://team.example/v1"),+ ({"api_key": ""}, "team-openai-key", "https://team.example/v1"),+ ({"api_key": " "}, "team-openai-key", "https://team.example/v1"),+ ({"api_key": "\n"}, "team-openai-key", "https://team.example/v1"),+ ({"api_key": "sk-forwarded"}, "sk-forwarded", "https://team.example/v1"),+ ({"api_base": "https://caller.example/v1"}, "team-openai-key", "https://team.example/v1"),+ (+ {"api_key": "sk-forwarded", "api_base": "https://caller.example/v1"},+ "sk-forwarded",+ "https://caller.example/v1",+ ),+ ({"api_key": 123}, "team-openai-key", "https://team.example/v1"),+ (+ {"api_key": "sk-forwarded", "api_base": ["https://caller.example/v1"]},+ "sk-forwarded",+ "https://team.example/v1",+ ),+ ({"api_key": "sk-forwarded", "api_base": " "}, "sk-forwarded", "https://team.example/v1"),+ ({"litellm_credential_name": "no-such-credential"}, "team-openai-key", "https://team.example/v1"),+ ({"api_key": "sk-forwarded\n", "drop_params": True}, "team-openai-key", "https://team.example/v1"),+ ({"api_key": "sk-for warded"}, "sk-for warded", "https://team.example/v1"),+ ],+)+def test_the_team_key_only_goes_to_the_team_host_unless_the_request_brings_its_own_key(+ request_credentials: dict[str, object], sent_api_key: str, sent_api_base: str+):+ data: Final[dict[str, object]] = dict(request_credentials)++ _apply_team_a_openai_credentials(data)++ assert (data.get("api_key"), data.get("api_base")) == (sent_api_key, sent_api_base)++[email protected]("api_key", ["sk-forwarded\n", " sk-forwarded", "\u200b", "sk-forwarded\u00a0"])+def test_a_request_key_that_cannot_be_an_http_header_is_a_bad_request(api_key: str):+ data: Final[dict[str, object]] = {"api_key": api_key}++ with pytest.raises(HTTPException) as refused:+ _apply_team_a_openai_credentials(data)++ assert refused.value.status_code == 400+ assert api_key not in str(refused.value.detail)+++def _apply_team_a_openai_credentials(data: dict[str, object]) -> None:+ apply_team_provider_credentials(+ data=data,+ llm_router=Router(+ model_list=[+ {+ "model_name": "openai/*",+ "litellm_params": {+ "model": "openai/*",+ "api_key": "team-openai-key",+ "api_base": "https://team.example/v1",+ },+ "model_info": {"id": "team-a-openai", "team_id": "team-a"},+ }+ ]+ ),+ user_api_key_dict=UserAPIKeyAuth(+ api_key="test-key", user_id="test-user", team_id="team-a", team_models=["openai/*"], models=["gpt-4o"]+ ),+ custom_llm_provider="openai",+ )+++def _team_openai_deployment(+ deployment_id: str, api_key: str, created_at: datetime | None = None, db_model: bool = True+) -> dict[str, object]:+ return {+ "model_name": f"team-gpt-{deployment_id}",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": api_key},+ "model_info": {"id": deployment_id, "team_id": "team-a", "db_model": db_model}+ | ({} if created_at is None else {"created_at": created_at}),+ }++[email protected]("deployment_ids", [("deployment-a", "deployment-b"), ("deployment-b", "deployment-a")])+def test_a_team_with_two_openai_deployments_resolves_the_same_one_in_any_router_order(+ deployment_ids: tuple[str, str],+):+ router: Final = Router(+ model_list=[_team_openai_deployment(deployment_id, f"{deployment_id}-key") for deployment_id in deployment_ids]+ )++ credentials: Final = get_team_provider_credentials(+ llm_router=router,+ user_api_key_dict=UserAPIKeyAuth(api_key="test-key", user_id="test-user", team_id="team-a"),+ custom_llm_provider="openai",+ include_accessible_deployments=False,+ )++ assert credentials is not None+ assert credentials["api_key"] == "deployment-a-key"++[email protected]("newer_first", [True, False])+def test_a_team_keeps_its_older_openai_deployment_when_a_newer_one_has_a_lower_id(newer_first: bool):+ older: Final = _team_openai_deployment("deployment-z", "older-key", datetime(2026, 1, 1, tzinfo=timezone.utc))+ newer: Final = _team_openai_deployment("deployment-a", "newer-key", datetime(2026, 6, 1, tzinfo=timezone.utc))+ router: Final = Router(model_list=[newer, older] if newer_first else [older, newer])++ credentials: Final = get_team_provider_credentials(+ llm_router=router,+ user_api_key_dict=UserAPIKeyAuth(api_key="test-key", user_id="test-user", team_id="team-a"),+ custom_llm_provider="openai",+ include_accessible_deployments=False,+ )++ assert credentials is not None+ assert credentials["api_key"] == "older-key"+++def test_a_team_keeps_its_first_config_file_openai_deployment_over_older_db_ones():+ db_deployment: Final = _team_openai_deployment("deployment-a", "db-key", datetime(2020, 1, 1, tzinfo=timezone.utc))+ config_deployments: Final = tuple(+ _team_openai_deployment(deployment_id, f"{deployment_id}-key", db_model=False)+ for deployment_id in ("deployment-z", "deployment-b")+ )+ router: Final = Router(model_list=[db_deployment, *config_deployments])++ credentials: Final = get_team_provider_credentials(+ llm_router=router,+ user_api_key_dict=UserAPIKeyAuth(api_key="test-key", user_id="test-user", team_id="team-a"),+ custom_llm_provider="openai",+ include_accessible_deployments=False,+ )++ assert credentials is not None+ assert credentials["api_key"] == "deployment-z-key"diff --git a/tests/unit/proxy/rag_endpoints/test_rag_endpoints.py b/tests/unit/proxy/rag_endpoints/test_rag_endpoints.pyindex 2d654ea28ec..d9f3ceda1ed 100644--- a/tests/unit/proxy/rag_endpoints/test_rag_endpoints.py+++ b/tests/unit/proxy/rag_endpoints/test_rag_endpoints.py@@ -1,21 +1,37 @@"""Tests for RAG proxy endpoints.--Covers:-- internal_user_viewer restriction: can only ingest to existing vector stores (must provide vector_store_id)"""import ioimport json+from collections.abc import Iterator, Mapping, Sequence+from typing import Finalfrom unittest.mock import AsyncMock, MagicMock, patch+import httpximport pytest+import respxfrom fastapi.testclient import TestClientimport litellm+from litellm import Routerfrom litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuthfrom litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.proxy_server import app+from litellm.types.vector_stores import LiteLLM_ManagedVectorStore+from litellm.vector_stores.vector_store_registry import VectorStoreRegistry++_TEAM_PROVIDER_KEY: Final = "team-openai-key"+_REGISTRY_PROVIDER_KEY: Final = "registry-openai-key"+_ENVIRONMENT_OPENAI_KEY: Final = "environment-openai-key"+_TEAM_ID: Final = "team-a"+_TEAM_OPENAI_BASE: Final = "https://team-openai.example/v1"+_REGISTRY_OPENAI_BASE: Final = "https://registry-openai.example/v1"+_OPENAI_SEARCH_PAGE: Final = {"object": "vector_store.search_results.page", "search_query": "q", "data": []}+_BEDROCK_KNOWLEDGE_BASE_ID: Final = "KB12345678"+_CALLER_AWS_ACCESS_KEY: Final = "caller-access-key"+_TEAM_AWS_ACCESS_KEY: Final = "team-access-key"+_HEADER_UNSAFE_PROVIDER_KEY: Final = "sk-forwarded\u00a0".encode("latin-1")@pytest.fixture@@ -48,31 +64,32 @@ def client_internal_user():app.dependency_overrides = original_overrides-def test_internal_user_viewer_rag_ingest_without_vector_store_id_rejected(- client_internal_user_viewer,-):- """- internal_user_viewer cannot create new vector stores - must provide vector_store_id.- """- # Form upload without vector_store_id (would create new store)- response = client_internal_user_viewer.post(- "/v1/rag/ingest",- files={"file": ("sample.txt", io.BytesIO(b"test content"), "text/plain")},- data={- "request": '{"ingest_options":{"vector_store":{"custom_llm_provider":"openai"}}}'- },- )+def client_team_a() -> Iterator[TestClient]:+ mock_auth: Final = UserAPIKeyAuth(user_id="test_team_user", team_id=_TEAM_ID)+ original_overrides: Final = app.dependency_overrides.copy()+ app.dependency_overrides[user_api_key_auth] = lambda: mock_auth+ try:+ yield TestClient(app)+ finally:+ app.dependency_overrides = original_overrides- assert response.status_code == 403- detail = response.json()- assert "detail" in detail- error_msg = (- detail["detail"]["error"]- if isinstance(detail["detail"], dict)- else str(detail["detail"])- )- assert "internal_user_viewer" in error_msg- assert "vector_store_id" in error_msg++def test_internal_user_viewer_rag_ingest_without_vector_store_id_allowed(client_internal_user_viewer):+ with patch(+ "litellm.proxy.rag_endpoints.endpoints.litellm.aingest",+ new_callable=AsyncMock,+ return_value={"status": "completed", "vector_store_id": "vs_new", "file_id": "file_123"},+ ) as mock_aingest:+ response: Final = client_internal_user_viewer.post(+ "/v1/rag/ingest",+ files={"file": ("sample.txt", io.BytesIO(b"test content"), "text/plain")},+ data={"request": '{"ingest_options":{"vector_store":{"custom_llm_provider":"openai"}}}'},+ )++ assert response.status_code == 200, response.json()+ assert response.json()["status"] == "completed"+ mock_aingest.assert_awaited_once()def test_internal_user_viewer_rag_ingest_with_vector_store_id_passes_check(@@ -97,8 +114,7 @@ def test_internal_user_viewer_rag_ingest_with_vector_store_id_passes_check(# Should not be 403 (role check passed)assert response.status_code != 403, (- f"internal_user_viewer with vector_store_id should pass role check. "- f"Response: {response.json()}"+ f"internal_user_viewer with vector_store_id should pass role check. Response: {response.json()}")@@ -114,15 +130,12 @@ def test_internal_user_rag_ingest_without_vector_store_id_allowed(client_internaresponse = client_internal_user.post("/v1/rag/ingest",files={"file": ("sample.txt", io.BytesIO(b"test content"), "text/plain")},- data={- "request": '{"ingest_options":{"vector_store":{"custom_llm_provider":"openai"}}}'- },+ data={"request": '{"ingest_options":{"vector_store":{"custom_llm_provider":"openai"}}}'},)# Should not be 403assert response.status_code != 403, (- f"internal_user should be allowed to create new vector stores. "- f"Response: {response.json()}"+ f"internal_user should be allowed to create new vector stores. Response: {response.json()}")@@ -170,13 +183,13 @@ def test_rag_ingest_blocks_clientside_credentials(client_internal_user, blocked_},},)- assert (- response.status_code == 400- ), f"Expected 400 when '{blocked_field}' is set clientside, got {response.status_code}: {response.json()}"+ assert response.status_code == 400, (+ f"Expected 400 when '{blocked_field}' is set clientside, got {response.status_code}: {response.json()}"+ )body = response.json()- assert blocked_field in str(- body- ), f"Response should mention '{blocked_field}': {body}"+ assert blocked_field in str(body), f"Response should mention '{blocked_field}': {body}"++class TestRagIngestSSRFBlocked:"""aws_sts_endpoint and related credential-redirect fields must be rejected@@ -193,9 +206,7 @@ class TestRagIngestSSRFBlocked:("aws_bedrock_runtime_endpoint", "https://attacker.example/bedrock"),],)- def test_ssrf_field_in_vector_store_config_rejected(- self, field, value, client_internal_user- ):+ def test_ssrf_field_in_vector_store_config_rejected(self, field, value, client_internal_user):payload = {"file_url": "https://example.com/doc.pdf","ingest_options": {@@ -215,9 +226,7 @@ class TestRagIngestSSRFBlocked:)body = response.json()detail = body.get("detail", {})- error_text = (- detail.get("error", "") if isinstance(detail, dict) else str(detail)- )+ error_text = detail.get("error", "") if isinstance(detail, dict) else str(detail)assert field in error_text, f"Error should name the offending field: {error_text}"def test_clean_bedrock_ingest_options_not_rejected(self, client_internal_user):@@ -230,14 +239,10 @@ class TestRagIngestSSRFBlocked:"/v1/rag/ingest",json={"file_url": "https://example.com/doc.pdf",- "ingest_options": {- "vector_store": {"custom_llm_provider": "bedrock"}- },+ "ingest_options": {"vector_store": {"custom_llm_provider": "bedrock"}},},)- assert response.status_code != 400, (- f"Clean Bedrock ingest_options should not be rejected: {response.json()}"- )+ assert response.status_code != 400, f"Clean Bedrock ingest_options should not be rejected: {response.json()}"S3_REGISTRY_STORE = {@@ -292,10 +297,20 @@ def _registry_with(store):return registry-def _ingest_form(vector_store):+def _ingest_form(vector_store, **request_fields):return {"files": {"file": ("sample.txt", io.BytesIO(b"test content"), "text/plain")},- "data": {"request": json.dumps({"ingest_options": {"vector_store": vector_store}})},+ "data": {"request": json.dumps({"ingest_options": {"vector_store": vector_store}, **request_fields})},+ }+++def _ingest_json(vector_store, **request_fields):+ return {+ "json": {+ "file_url": "https://example.com/doc.txt",+ "ingest_options": {"vector_store": vector_store},+ **request_fields,+ }}@@ -320,6 +335,557 @@ def _patched_prisma_client(prisma_client):)+def _team_provider_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "openai/team-provider",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": _TEAM_PROVIDER_KEY,+ "api_base": _TEAM_OPENAI_BASE,+ },+ "model_info": {"team_id": _TEAM_ID},+ },+ _completion_deployment(),+ ]+ )+++def _completion_deployment() -> dict[str, object]:+ return {+ "model_name": "gpt-4o-mini",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "completion-key",+ "mock_response": "hello",+ },+ }+++def _team_bedrock_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "bedrock/team-provider",+ "litellm_params": {+ "model": "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",+ "aws_region_name": "us-west-2",+ "aws_access_key_id": _TEAM_AWS_ACCESS_KEY,+ "aws_secret_access_key": "team-secret-key",+ },+ "model_info": {"team_id": _TEAM_ID},+ },+ _completion_deployment(),+ ]+ )+++def _managed_openai_store(vector_store_id: str, litellm_params: Mapping[str, object]) -> LiteLLM_ManagedVectorStore:+ return LiteLLM_ManagedVectorStore(+ vector_store_id=vector_store_id,+ custom_llm_provider="openai",+ litellm_credential_name=None,+ litellm_params=dict(litellm_params),+ )+++def _post_rag_query(+ client: TestClient,+ *,+ retrieval_config: Mapping[str, object],+ managed_stores: Sequence[LiteLLM_ManagedVectorStore],+ router: Router,+ headers: Mapping[str, str | bytes] | None = None,+ body: Mapping[str, object] | None = None,+) -> httpx.Response:+ with (+ patch.object( # test-quality-ok: seeds the real managed-store registry the query path reads+ litellm,+ "vector_store_registry",+ VectorStoreRegistry(vector_stores=list(managed_stores)),+ ),+ patch("litellm.proxy.proxy_server.llm_router", router),+ _patched_prisma_client(None),+ ):+ return client.post(+ "/v1/rag/query",+ json={+ "model": "gpt-4o-mini",+ "messages": [{"role": "user", "content": "hello"}],+ "retrieval_config": dict(retrieval_config),+ **(body or {}),+ },+ headers=dict(headers or {}),+ )+++def test_rag_ingest_forwards_team_provider_credentials_without_persisting_them(client_team_a):+ router: Final = _team_provider_router()+ prisma_client: Final = MagicMock()+ managed_vector_store_table: Final = prisma_client.db.litellm_managedvectorstorestable+ managed_vector_store_table.find_unique = AsyncMock(return_value=None)+ created_row: Final = MagicMock()+ created_row.model_dump.return_value = {+ "vector_store_id": "vs_new",+ "custom_llm_provider": "openai",+ "litellm_params": "{}",+ "vector_store_metadata": "{}",+ }+ managed_vector_store_table.create = AsyncMock(return_value=created_row)+ aingest_patch, registry_patch = _patched_ingest_boundary(+ None,+ {"status": "completed", "vector_store_id": "vs_new", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", router),+ _patched_prisma_client(prisma_client),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ **_ingest_form({"custom_llm_provider": "openai"}),+ )++ assert response.status_code == 200, response.json()+ forwarded: Final = mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]+ assert forwarded["api_key"] == _TEAM_PROVIDER_KEY+ assert forwarded["api_base"] == _TEAM_OPENAI_BASE+ managed_vector_store_table.create.assert_awaited_once()+ saved_data: Final = managed_vector_store_table.create.await_args.kwargs["data"]+ assert saved_data["vector_store_id"] == "vs_new"+ assert _TEAM_PROVIDER_KEY not in json.dumps(saved_data, default=str)+++def test_rag_ingest_uses_the_forwarded_provider_key_over_team_provider_credentials(client_team_a):+ forwarded_provider_key: Final = "sk-forwarded-provider-key"+ aingest_patch, registry_patch = _patched_ingest_boundary(+ None,+ {"status": "completed", "vector_store_id": "vs_new", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", _team_provider_router()),+ patch.dict("litellm.proxy.proxy_server.general_settings", {"forward_llm_provider_auth_headers": True}),+ _patched_prisma_client(None),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ headers={"Authorization": "Bearer sk-litellm-virtual-key", "x-api-key": forwarded_provider_key},+ **_ingest_form({"custom_llm_provider": "openai"}),+ )++ assert response.status_code == 200, response.json()+ forwarded: Final = mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]+ assert forwarded["api_key"] == forwarded_provider_key+ assert forwarded["api_base"] == _TEAM_OPENAI_BASE++[email protected]("ingest_request", [_ingest_form, _ingest_json])+def test_rag_ingest_drop_params_drops_a_forwarded_key_that_cannot_be_an_http_header(client_team_a, ingest_request):+ aingest_patch, registry_patch = _patched_ingest_boundary(+ None,+ {"status": "completed", "vector_store_id": "vs_new", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", _team_provider_router()),+ patch.dict("litellm.proxy.proxy_server.general_settings", {"forward_llm_provider_auth_headers": True}),+ _patched_prisma_client(None),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ headers={"Authorization": "Bearer sk-litellm-virtual-key", "x-api-key": _HEADER_UNSAFE_PROVIDER_KEY},+ **ingest_request({"custom_llm_provider": "openai"}, drop_params=True),+ )++ assert response.status_code == 200, response.json()+ forwarded: Final = mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]+ assert forwarded["api_key"] == _TEAM_PROVIDER_KEY+ assert forwarded["api_base"] == _TEAM_OPENAI_BASE++[email protected]("unread_request_field", ["not json", json.dumps({"drop_params": False})])+def test_rag_ingest_json_body_ignores_a_request_field_it_does_not_read(client_team_a, unread_request_field):+ aingest_patch, registry_patch = _patched_ingest_boundary(+ None,+ {"status": "completed", "vector_store_id": "vs_new", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", _team_provider_router()),+ patch.dict("litellm.proxy.proxy_server.general_settings", {"forward_llm_provider_auth_headers": True}),+ _patched_prisma_client(None),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ headers={"Authorization": "Bearer sk-litellm-virtual-key", "x-api-key": _HEADER_UNSAFE_PROVIDER_KEY},+ **_ingest_json({"custom_llm_provider": "openai"}, drop_params=True, request=unread_request_field),+ )++ assert response.status_code == 200, response.json()+ assert mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]["api_key"] == _TEAM_PROVIDER_KEY+++def test_rag_ingest_caller_credential_name_suppresses_team_provider_credentials(client_team_a):+ aingest_patch, registry_patch = _patched_ingest_boundary(+ None,+ {"status": "completed", "vector_store_id": "vs_new", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", _team_provider_router()),+ _patched_prisma_client(None),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ **_ingest_form({"custom_llm_provider": "openai", "litellm_credential_name": "caller-openai"}),+ )++ assert response.status_code == 200, response.json()+ forwarded: Final = mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]+ assert forwarded["litellm_credential_name"] == "caller-openai"+ assert "api_key" not in forwarded+++def test_rag_ingest_managed_store_credentials_override_team_provider_credentials(client_team_a):+ managed_store: Final = _managed_openai_store("registry-store-with-key", {"api_key": _REGISTRY_PROVIDER_KEY})+ aingest_patch, registry_patch = _patched_ingest_boundary(+ managed_store,+ {"status": "completed", "vector_store_id": "registry-store-with-key", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", _team_provider_router()),+ patch(+ "litellm.proxy.vector_store_endpoints.utils.can_user_access_vector_store",+ new=AsyncMock(return_value=True),+ ),+ _patched_prisma_client(None),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ **_ingest_form({"vector_store_id": "registry-store-with-key"}),+ )++ assert response.status_code == 200, response.json()+ forwarded: Final = mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]+ assert forwarded["api_key"] == _REGISTRY_PROVIDER_KEY+ assert forwarded["api_key"] != _TEAM_PROVIDER_KEY+++def test_rag_ingest_managed_store_without_credentials_uses_team_provider_credentials(client_team_a):+ managed_store: Final = _managed_openai_store("registry-store-without-key", {})+ aingest_patch, registry_patch = _patched_ingest_boundary(+ managed_store,+ {"status": "completed", "vector_store_id": "registry-store-without-key", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", _team_provider_router()),+ patch(+ "litellm.proxy.vector_store_endpoints.utils.can_user_access_vector_store",+ new=AsyncMock(return_value=True),+ ),+ _patched_prisma_client(None),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ **_ingest_form({"vector_store_id": "registry-store-without-key"}),+ )++ assert response.status_code == 200, response.json()+ forwarded: Final = mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]+ assert forwarded["api_key"] == _TEAM_PROVIDER_KEY++[email protected]("blank_credential_name", [None, "", " "])+def test_rag_ingest_blank_caller_credential_name_uses_team_provider_credentials(client_team_a, blank_credential_name):+ aingest_patch, registry_patch = _patched_ingest_boundary(+ None,+ {"status": "completed", "vector_store_id": "vs_new", "file_id": "file_123"},+ )++ with (+ aingest_patch as mock_aingest,+ registry_patch,+ patch("litellm.proxy.proxy_server.llm_router", _team_provider_router()),+ _patched_prisma_client(None),+ ):+ response: Final = client_team_a.post(+ "/v1/rag/ingest",+ **_ingest_form({"custom_llm_provider": "openai", "litellm_credential_name": blank_credential_name}),+ )++ assert response.status_code == 200, response.json()+ forwarded: Final = mock_aingest.await_args.kwargs["ingest_options"]["vector_store"]+ assert forwarded["api_key"] == _TEAM_PROVIDER_KEY+ assert forwarded["api_base"] == _TEAM_OPENAI_BASE+++def test_rag_ingest_failed_upstream_status_is_returned_without_persisting_store(client_internal_user):+ prisma_client: Final = MagicMock()+ managed_vector_store_table: Final = prisma_client.db.litellm_managedvectorstorestable+ managed_vector_store_table.find_unique = AsyncMock(return_value=None)+ managed_vector_store_table.create = AsyncMock()+ with (+ patch(+ "litellm.proxy.rag_endpoints.endpoints.litellm.aingest",+ new=AsyncMock(+ return_value={+ "id": "ingest_abc",+ "status": "failed",+ "error": "unauthorized",+ "error_status_code": 401,+ }+ ),+ ),+ patch("litellm.vector_store_registry", None),+ _patched_prisma_client(prisma_client),+ ):+ response: Final = client_internal_user.post(+ "/v1/rag/ingest",+ **_ingest_form({"custom_llm_provider": "openai"}),+ )++ assert response.status_code == 401, response.json()+ assert response.json() == {"detail": {"id": "ingest_abc", "status": "failed", "error": "unauthorized"}}+ managed_vector_store_table.create.assert_not_called()++[email protected]("httpx_transport")+ "caller_fields",+ [+ {},+ {"api_key": None},+ {"api_base": None},+ {"api_key": "sk-caller-key-the-search-never-uses"},+ {"custom_llm_provider": None},+ ],+)+def test_rag_query_forwards_team_provider_credentials_to_unmanaged_search(+ client_team_a: TestClient, respx_mock: respx.MockRouter, caller_fields: Mapping[str, object]+) -> None:+ search: Final = respx_mock.post(f"{_TEAM_OPENAI_BASE}/vector_stores/provider-native-store/search").respond(+ json=_OPENAI_SEARCH_PAGE+ )++ response: Final = _post_rag_query(+ client_team_a,+ retrieval_config={"vector_store_id": "provider-native-store", "custom_llm_provider": "openai", **caller_fields},+ managed_stores=(),+ router=_team_provider_router(),+ )++ assert response.status_code == 200, response.json()+ assert search.call_count == 1+ assert search.calls.last.request.headers["authorization"] == f"Bearer {_TEAM_PROVIDER_KEY}"++[email protected]("httpx_transport")+def test_rag_query_managed_store_credentials_override_team_provider_credentials(+ client_team_a: TestClient, respx_mock: respx.MockRouter+) -> None:+ search: Final = respx_mock.post(f"{_REGISTRY_OPENAI_BASE}/vector_stores/registry-store-with-key/search").respond(+ json=_OPENAI_SEARCH_PAGE+ )++ response: Final = _post_rag_query(+ client_team_a,+ retrieval_config={"vector_store_id": "registry-store-with-key"},+ managed_stores=(+ _managed_openai_store(+ "registry-store-with-key",+ {"api_key": _REGISTRY_PROVIDER_KEY, "api_base": _REGISTRY_OPENAI_BASE},+ ),+ ),+ router=_team_provider_router(),+ )++ assert response.status_code == 200, response.json()+ assert search.call_count == 1+ assert search.calls.last.request.headers["authorization"] == f"Bearer {_REGISTRY_PROVIDER_KEY}"++[email protected]("httpx_transport")+def test_rag_query_managed_store_without_credentials_uses_team_provider_credentials(+ client_team_a: TestClient, respx_mock: respx.MockRouter+) -> None:+ search: Final = respx_mock.post(f"{_TEAM_OPENAI_BASE}/vector_stores/registry-store-without-key/search").respond(+ json=_OPENAI_SEARCH_PAGE+ )++ response: Final = _post_rag_query(+ client_team_a,+ retrieval_config={"vector_store_id": "registry-store-without-key"},+ managed_stores=(_managed_openai_store("registry-store-without-key", {}),),+ router=_team_provider_router(),+ )++ assert response.status_code == 200, response.json()+ assert search.call_count == 1+ assert search.calls.last.request.headers["authorization"] == f"Bearer {_TEAM_PROVIDER_KEY}"++[email protected]("httpx_transport")[email protected]("blank_key", ["", " "])+def test_rag_query_managed_store_with_an_empty_key_uses_team_provider_credentials(+ client_team_a: TestClient, respx_mock: respx.MockRouter, blank_key: str+) -> None:+ search: Final = respx_mock.post(f"{_TEAM_OPENAI_BASE}/vector_stores/registry-store-blank-key/search").respond(+ json=_OPENAI_SEARCH_PAGE+ )++ response: Final = _post_rag_query(+ client_team_a,+ retrieval_config={"vector_store_id": "registry-store-blank-key"},+ managed_stores=(_managed_openai_store("registry-store-blank-key", {"api_key": blank_key}),),+ router=_team_provider_router(),+ )++ assert response.status_code == 200, response.json()+ assert search.call_count == 1+ assert search.calls.last.request.headers["authorization"] == f"Bearer {_TEAM_PROVIDER_KEY}"++[email protected]("httpx_transport")+def test_rag_query_without_a_team_deployment_keeps_the_environment_openai_credentials(+ client_internal_user: TestClient, respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("OPENAI_API_KEY", _ENVIRONMENT_OPENAI_KEY)+ for unset in ("OPENAI_BASE_URL", "OPENAI_API_BASE"):+ monkeypatch.delenv(unset, raising=False)+ search: Final = respx_mock.post("https://api.openai.com/v1/vector_stores/provider-native-store/search").respond(+ json=_OPENAI_SEARCH_PAGE+ )++ response: Final = _post_rag_query(+ client_internal_user,+ retrieval_config={"vector_store_id": "provider-native-store", "custom_llm_provider": "openai"},+ managed_stores=(),+ router=_team_provider_router(),+ )++ assert response.status_code == 200, response.json()+ assert search.call_count == 1+ assert search.calls.last.request.headers["authorization"] == f"Bearer {_ENVIRONMENT_OPENAI_KEY}"++[email protected]("httpx_transport")+def test_rag_query_search_uses_the_forwarded_provider_key_over_team_provider_credentials(+ client_team_a: TestClient, respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ forwarded_provider_key: Final = "sk-forwarded-provider-key"+ monkeypatch.setenv("OPENAI_API_KEY", _ENVIRONMENT_OPENAI_KEY)+ for unset in ("OPENAI_BASE_URL", "OPENAI_API_BASE"):+ monkeypatch.delenv(unset, raising=False)+ search: Final = respx_mock.post(f"{_TEAM_OPENAI_BASE}/vector_stores/provider-native-store/search").respond(+ json=_OPENAI_SEARCH_PAGE+ )++ with patch.dict("litellm.proxy.proxy_server.general_settings", {"forward_llm_provider_auth_headers": True}):+ response: Final = _post_rag_query(+ client_team_a,+ retrieval_config={"vector_store_id": "provider-native-store", "custom_llm_provider": "openai"},+ managed_stores=(),+ router=_team_provider_router(),+ headers={"Authorization": "Bearer sk-litellm-virtual-key", "x-api-key": forwarded_provider_key},+ )++ assert response.status_code == 200, response.json()+ assert search.call_count == 1+ assert search.calls.last.request.headers["authorization"] == f"Bearer {forwarded_provider_key}"++[email protected]("httpx_transport")+def test_rag_query_drop_params_drops_a_forwarded_key_that_cannot_be_an_http_header(+ client_team_a: TestClient, respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("OPENAI_API_KEY", _ENVIRONMENT_OPENAI_KEY)+ for unset in ("OPENAI_BASE_URL", "OPENAI_API_BASE"):+ monkeypatch.delenv(unset, raising=False)+ search: Final = respx_mock.post(f"{_TEAM_OPENAI_BASE}/vector_stores/provider-native-store/search").respond(+ json=_OPENAI_SEARCH_PAGE+ )++ with patch.dict("litellm.proxy.proxy_server.general_settings", {"forward_llm_provider_auth_headers": True}):+ response: Final = _post_rag_query(+ client_team_a,+ retrieval_config={"vector_store_id": "provider-native-store", "custom_llm_provider": "openai"},+ managed_stores=(),+ router=_team_provider_router(),+ headers={"Authorization": "Bearer sk-litellm-virtual-key", "x-api-key": _HEADER_UNSAFE_PROVIDER_KEY},+ body={"drop_params": True},+ )++ assert response.status_code == 200, response.json()+ assert search.call_count == 1+ assert search.calls.last.request.headers["authorization"] == f"Bearer {_TEAM_PROVIDER_KEY}"+++ "retrieval_config, error",+ [+ ({"custom_llm_provider": "openai"}, "retrieval_config must contain 'vector_store_id'"),+ ({"vector_store_id": 7, "custom_llm_provider": "openai"}, "vector_store_id must be a non-empty string"),+ ],+)+def test_rag_query_names_what_is_wrong_with_the_vector_store_id(+ client_team_a: TestClient, retrieval_config: Mapping[str, object], error: str+) -> None:+ response: Final = _post_rag_query(+ client_team_a, retrieval_config=retrieval_config, managed_stores=(), router=_team_provider_router()+ )++ assert response.status_code == 400, response.json()+ assert error in response.text++[email protected]("httpx_transport")+def test_rag_query_bedrock_search_keeps_the_callers_region_and_credentials_over_team_deployment(+ client_team_a: TestClient, respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", _CALLER_AWS_ACCESS_KEY)+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "caller-secret-key")+ for unset in ("AWS_BEARER_TOKEN_BEDROCK", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_REGION_NAME", "AWS_REGION"):+ monkeypatch.delenv(unset, raising=False)+ retrieve: Final = respx_mock.post(+ url__regex=rf"^https://bedrock-agent-runtime\.[a-z0-9-]+\.amazonaws\.com/knowledgebases/{_BEDROCK_KNOWLEDGE_BASE_ID}/retrieve$"+ ).respond(json={"retrievalResults": []})++ response: Final = _post_rag_query(+ client_team_a,+ retrieval_config={+ "vector_store_id": _BEDROCK_KNOWLEDGE_BASE_ID,+ "custom_llm_provider": "bedrock",+ "aws_region_name": "us-east-1",+ },+ managed_stores=(),+ router=_team_bedrock_router(),+ )++ assert response.status_code == 200, response.json()+ assert retrieve.call_count == 1+ sent: Final = retrieve.calls.last.request+ assert sent.url.host == "bedrock-agent-runtime.us-east-1.amazonaws.com"+ assert f"Credential={_CALLER_AWS_ACCESS_KEY}/" in sent.headers["authorization"]++def test_rag_ingest_resolves_registry_store_provider_and_params(client_internal_user):aingest_patch, registry_patch = _patched_ingest_boundary(S3_REGISTRY_STORE, {"vector_store_id": "s3-store", "file_id": "file_123"}@@ -703,12 +1269,14 @@ def test_rag_query_returns_response_cost_header(client_internal_user):)mock_response._hidden_params["response_cost"] = 3.45e-06- with patch(- "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",- new_callable=AsyncMock,- return_value=mock_response,- ), patch("litellm.vector_store_registry", None), patch(- "litellm.proxy.proxy_server.prisma_client", None+ with (+ patch(+ "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",+ new_callable=AsyncMock,+ return_value=mock_response,+ ),+ patch("litellm.vector_store_registry", None),+ patch("litellm.proxy.proxy_server.prisma_client", None),):response = client_internal_user.post("/v1/rag/query",@@ -742,7 +1310,9 @@ def test_rag_query_surfaces_upstream_status_code(client_internal_user, upstream_new=AsyncMock(side_effect=upstream_error),),patch("litellm.vector_store_registry", None), # test-quality-ok: proxy module global, no injection seam- patch("litellm.proxy.proxy_server.prisma_client", None), # test-quality-ok: proxy module global, no injection seam+ patch(+ "litellm.proxy.proxy_server.prisma_client", None+ ), # test-quality-ok: proxy module global, no injection seam):response = client_internal_user.post("/v1/rag/query",@@ -779,10 +1349,14 @@ def test_rag_query_stream_returns_event_stream(client_internal_user):api_key="test-key",)- with patch(- "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",- new=AsyncMock(side_effect=fake_aquery),- ), patch("litellm.vector_store_registry", None), patch("litellm.proxy.proxy_server.prisma_client", None):+ with (+ patch(+ "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",+ new=AsyncMock(side_effect=fake_aquery),+ ),+ patch("litellm.vector_store_registry", None),+ patch("litellm.proxy.proxy_server.prisma_client", None),+ ):response = client_internal_user.post("/v1/rag/query",json={@@ -825,7 +1399,9 @@ def test_rag_query_stream_pings_while_retrieval_is_still_running(client_internalnew=AsyncMock(side_effect=slow_aquery),),patch("litellm.vector_store_registry", None), # test-quality-ok: proxy module global, no injection seam- patch("litellm.proxy.proxy_server.prisma_client", None), # test-quality-ok: proxy module global, no injection seam+ patch(+ "litellm.proxy.proxy_server.prisma_client", None+ ), # test-quality-ok: proxy module global, no injection seam):response = client_internal_user.post("/v1/rag/query",@@ -849,9 +1425,7 @@ def test_rag_query_stream_pings_while_retrieval_is_still_running(client_internalassert response.text.endswith("data: [DONE]\n\n")-def test_rag_query_stream_keeps_response_headers_when_retrieval_beats_the_keepalive(- client_internal_user, monkeypatch-):+def test_rag_query_stream_keeps_response_headers_when_retrieval_beats_the_keepalive(client_internal_user, monkeypatch):import litellm as litellm_modulemonkeypatch.setattr(litellm_module, "sse_keepalive_ping_interval_seconds", 5)@@ -873,7 +1447,9 @@ def test_rag_query_stream_keeps_response_headers_when_retrieval_beats_the_keepalnew=AsyncMock(side_effect=fast_aquery),),patch("litellm.vector_store_registry", None), # test-quality-ok: proxy module global, no injection seam- patch("litellm.proxy.proxy_server.prisma_client", None), # test-quality-ok: proxy module global, no injection seam+ patch(+ "litellm.proxy.proxy_server.prisma_client", None+ ), # test-quality-ok: proxy module global, no injection seam):response = client_internal_user.post("/v1/rag/query",@@ -925,13 +1501,17 @@ def test_rag_query_merges_managed_store_params(client_internal_user):model="gpt-4o-mini",)- with patch( # test-quality-ok: aquery is the endpoint's downstream boundary; the forwarded config is what the test asserts- "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",- new_callable=AsyncMock,- return_value=mock_response,- ) as mock_aquery, patch.object(litellm, "vector_store_registry", mock_registry), patch( # test-quality-ok: seeds the managed-store registry the merge under test reads and grants access so real store resolution runs- "litellm.proxy.vector_store_endpoints.utils.can_user_access_vector_store",- new=AsyncMock(return_value=True),+ with (+ patch( # test-quality-ok: aquery is the endpoint's downstream boundary; the forwarded config is what the test asserts+ "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",+ new_callable=AsyncMock,+ return_value=mock_response,+ ) as mock_aquery,+ patch.object(litellm, "vector_store_registry", mock_registry),+ patch( # test-quality-ok: seeds the managed-store registry the merge under test reads and grants access so real store resolution runs+ "litellm.proxy.vector_store_endpoints.utils.can_user_access_vector_store",+ new=AsyncMock(return_value=True),+ ),):response = client_internal_user.post("/v1/rag/query",@@ -971,13 +1551,17 @@ def test_rag_query_store_params_win_over_user_retrieval_config(client_internal_umodel="gpt-4o-mini",)- with patch( # test-quality-ok: aquery is the endpoint's downstream boundary; the forwarded config is what the test asserts- "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",- new_callable=AsyncMock,- return_value=mock_response,- ) as mock_aquery, patch.object(litellm, "vector_store_registry", mock_registry), patch( # test-quality-ok: seeds the managed-store registry the merge under test reads and grants access so real store resolution runs- "litellm.proxy.vector_store_endpoints.utils.can_user_access_vector_store",- new=AsyncMock(return_value=True),+ with (+ patch( # test-quality-ok: aquery is the endpoint's downstream boundary; the forwarded config is what the test asserts+ "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",+ new_callable=AsyncMock,+ return_value=mock_response,+ ) as mock_aquery,+ patch.object(litellm, "vector_store_registry", mock_registry),+ patch( # test-quality-ok: seeds the managed-store registry the merge under test reads and grants access so real store resolution runs+ "litellm.proxy.vector_store_endpoints.utils.can_user_access_vector_store",+ new=AsyncMock(return_value=True),+ ),):response = client_internal_user.post("/v1/rag/query",@@ -1164,9 +1748,7 @@ class TestVectorStoreUploadControls:content=b"benign document text\n",content_type="text/plain",)- _options, file_data, _url, _file_id = await parse_rag_ingest_request(- request, scanner=EicarTestMalwareScanner()- )+ _options, file_data, _url, _file_id = await parse_rag_ingest_request(request, scanner=EicarTestMalwareScanner())assert file_data is not Noneserver_filename, content_bytes, secured_content_type = file_dataassert server_filename != "../../etc/passwd"diff --git a/tests/unit/proxy/test_batch_x_litellm_model_encoding.py b/tests/unit/proxy/test_batch_x_litellm_model_encoding.pyindex f8c734c4efd..22fada05aa7 100644--- a/tests/unit/proxy/test_batch_x_litellm_model_encoding.py+++ b/tests/unit/proxy/test_batch_x_litellm_model_encoding.py@@ -10,6 +10,7 @@ from typing import Optionalfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from starlette.datastructures import Headers, QueryParamsfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.openai_files_endpoints.common_utils import (@@ -23,8 +24,8 @@ from litellm.types.utils import LiteLLMBatchdef _make_mock_request(headers: dict) -> MagicMock:"""Create a mock FastAPI Request with the given headers."""mock_request = MagicMock()- mock_request.headers = headers- mock_request.query_params = {}+ mock_request.headers = Headers(headers=headers)+ mock_request.query_params = QueryParams({})mock_request.url = MagicMock()mock_request.url.port = 4000mock_request.method = "POST"diff --git a/tests/unit/rag/ingestion/test_base_ingestion.py b/tests/unit/rag/ingestion/test_base_ingestion.pyindex d20b46d356b..63a0f0d7da5 100644--- a/tests/unit/rag/ingestion/test_base_ingestion.py+++ b/tests/unit/rag/ingestion/test_base_ingestion.py@@ -1,4 +1,5 @@from collections import UserString+from types import SimpleNamespacefrom typing import Finalimport httpx@@ -6,10 +7,18 @@ import pytestimport respximport litellm+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestionfrom litellm.rag.ingestion.gemini_ingestion import GeminiRAGIngestion+from litellm.rag.ingestion.openai_ingestion import OpenAIRAGIngestion+from litellm.rag.ingestion.s3_vectors_ingestion import S3VectorsRAGIngestion+from litellm.rag.ingestion.vertex_ai_ingestion import VertexAIRAGIngestionfrom litellm.types.utils import CredentialItem_FILE_URL: Final = "https://files.example/docs/report.pdf"+_GEMINI_API_BASE: Final = "https://gemini.example"+_GEMINI_STORE: Final = "fileSearchStores/docs-1"+_GEMINI_UPLOAD_SESSION_URL: Final = "https://gemini.example/upload/session-1"+_TEXT_FILE: Final = ("report.txt", b"plain text", "text/plain")_STORED_CREDENTIAL: Final = CredentialItem(credential_name="gemini-prod",credential_info={},@@ -17,6 +26,32 @@ _STORED_CREDENTIAL: Final = CredentialItem()+class _UnauthorizedIngestionError(Exception):+ status_code: Final = 401+++class _FailingStoreIngestion(BaseRAGIngestion):+ def __init__(self, failure: Exception) -> None:+ super().__init__(ingest_options={"vector_store": {}})+ self._failure = failure++ async def store(+ self,+ file_content: bytes | None,+ filename: str | None,+ content_type: str | None,+ chunks: list[str],+ embeddings: list[list[float]] | None,+ existing_file_id: str | None = None,+ ) -> tuple[str | None, str | None]:+ raise self._failure+++class _EmbeddingRouter:+ async def aembedding(self, model: str, input: list[str]) -> SimpleNamespace:+ return SimpleNamespace(data=[{"embedding": [0.1, 0.2]} for _ in input])++def _vector_store_options(litellm_credential_name: object) -> dict[str, object]:return {"custom_llm_provider": "gemini",@@ -99,3 +134,132 @@ async def test_upload_from_a_url_takes_the_content_type_from_the_response_headeruploaded: Final = await ingestion.upload(file_url=_FILE_URL)assert uploaded == ("report.pdf", b"%PDF-1.7", expected_content_type, None)+++ ("failure", "expected_status_code"),+ [+ (_UnauthorizedIngestionError("unauthorized"), 401),+ (RuntimeError("ingestion failed"), None),+ ],+)+async def test_ingest_response_preserves_integer_exception_status_code(+ failure: Exception,+ expected_status_code: int | None,+) -> None:+ response: Final = await _FailingStoreIngestion(failure).ingest(+ file_data=("report.txt", b"plain text", "text/plain")+ )++ assert response["error_status_code"] == expected_status_code+++async def test_an_existing_file_id_on_a_store_that_cannot_take_one_fails_as_a_bad_request() -> None:+ response: Final = await _FailingStoreIngestion(RuntimeError("store must not run")).ingest(file_id="file-abc")++ assert response["status"] == "failed"+ assert response["error_status_code"] == 400+ assert "does not support ingesting an existing file_id" in str(response["error"])+++ ("ingestion_class", "ingest_kwargs"),+ [+ (OpenAIRAGIngestion, {"file_id": "file-abc"}),+ (VertexAIRAGIngestion, {"file_data": ("report.txt", b"plain text", "text/plain")}),+ ],+)+async def test_a_vector_store_config_missing_a_caller_field_fails_as_a_bad_request(+ ingestion_class: type[BaseRAGIngestion],+ ingest_kwargs: dict[str, object],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("VERTEXAI_PROJECT", raising=False)+ ingestion: Final = ingestion_class(ingest_options={"vector_store": {"api_key": "caller-key"}})++ response: Final = await ingestion.ingest(**ingest_kwargs)++ assert response["status"] == "failed"+ assert response["error_status_code"] == 400+++ ("vector_store_id", "upstream_statuses", "expected_status_code"),+ [+ (None, {"create_store": 401}, 401),+ (_GEMINI_STORE, {"start_upload": 429}, 429),+ (_GEMINI_STORE, {"upload": 503}, 503),+ ],+)+async def test_a_gemini_upstream_error_keeps_its_status_on_the_failed_ingest(+ monkeypatch: pytest.MonkeyPatch,+ respx_mock: respx.MockRouter,+ vector_store_id: str | None,+ upstream_statuses: dict[str, int],+ expected_status_code: int,+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()+ respx_mock.post(f"{_GEMINI_API_BASE}/v1beta/fileSearchStores").mock(+ return_value=httpx.Response(upstream_statuses.get("create_store", 200), json={"name": _GEMINI_STORE})+ )+ respx_mock.post(f"{_GEMINI_API_BASE}/upload/v1beta/{_GEMINI_STORE}:uploadToFileSearchStore").mock(+ return_value=httpx.Response(+ upstream_statuses.get("start_upload", 200), headers={"x-goog-upload-url": _GEMINI_UPLOAD_SESSION_URL}+ )+ )+ respx_mock.put(_GEMINI_UPLOAD_SESSION_URL).mock(+ return_value=httpx.Response(upstream_statuses.get("upload", 200), json={"name": f"{_GEMINI_STORE}/documents/d"})+ )+ vector_store: Final = {+ "custom_llm_provider": "gemini",+ "api_key": "test-key",+ "api_base": _GEMINI_API_BASE,+ **({"vector_store_id": vector_store_id} if vector_store_id else {}),+ }++ response: Final = await GeminiRAGIngestion(ingest_options={"vector_store": vector_store}).ingest(+ file_data=_TEXT_FILE+ )++ assert response["status"] == "failed"+ assert response["error_status_code"] == expected_status_code+++async def test_a_gemini_store_with_no_api_key_anywhere_fails_without_a_caller_error_status(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)+ monkeypatch.delenv("GOOGLE_API_KEY", raising=False)+ ingestion: Final = GeminiRAGIngestion(ingest_options={"vector_store": {"custom_llm_provider": "gemini"}})++ response: Final = await ingestion.ingest(file_data=_TEXT_FILE)++ assert response["status"] == "failed"+ assert response.get("error_status_code") is None+++ "vector_bucket_name",+ ["ab", "bucket_with_underscores"],+)+async def test_an_invalid_s3_vectors_bucket_name_fails_as_a_bad_request(vector_bucket_name: str) -> None:+ ingestion: Final = S3VectorsRAGIngestion(+ ingest_options={+ "embedding": {"model": "text-embedding-3-small"},+ "vector_store": {+ "custom_llm_provider": "s3_vectors",+ "aws_region_name": "us-west-2",+ "vector_bucket_name": vector_bucket_name,+ "dimension": 2,+ },+ },+ router=_EmbeddingRouter(),+ )++ response: Final = await ingestion.ingest(file_data=_TEXT_FILE)++ assert response["status"] == "failed"+ assert response["error_status_code"] == 400diff --git a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.test.tsxindex ff0706b24cb..9b7e60aa12a 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.test.tsx@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";import { describe, it, expect, vi, beforeEach } from "vitest";import CreateVectorStore from "./CreateVectorStore";import * as networking from "@/components/networking";+import { toast } from "@/lib/toast";// Mock the networking modulevi.mock("@/components/networking", () => ({@@ -215,6 +216,44 @@ describe("CreateVectorStore", () => {});});+ it("should report the created store and the failed file when a later file fails to ingest", async () => {+ const firstIngest = { id: "ingest-1", status: "completed", vector_store_id: "vs_123", file_id: "file_1" };+ vi.mocked(networking.ragIngestCall)+ .mockResolvedValueOnce(firstIngest)+ .mockRejectedValueOnce(new Error("upstream rejected the file"));+ const onSuccess = vi.fn();+ render(<CreateVectorStore accessToken="test-token" onSuccess={onSuccess} />);++ const uploadInput = document.querySelector('input[type="file"]') as HTMLInputElement;+ await act(async () => {+ fireEvent.change(uploadInput, {+ target: {+ files: [+ new File(["first"], "first.txt", { type: "text/plain" }),+ new File(["second"], "second.txt", { type: "text/plain" }),+ ],+ },+ });+ });+ await waitFor(() => {+ expect(screen.getByText("Uploaded Documents (2)")).toBeInTheDocument();+ });++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: /Create Vector Store/i }));+ });++ await waitFor(() => {+ expect(toast.warning).toHaveBeenCalledWith(+ "Vector store vs_123 was created with 1 document(s), but second.txt failed to ingest",+ { description: "upstream rejected the file" },+ );+ });+ expect(toast.fromError).not.toHaveBeenCalled();+ expect(onSuccess).toHaveBeenCalledWith("vs_123");+ expect(screen.getByText("Vector Store Created Successfully")).toBeInTheDocument();+ });+it("should exclude valkey from the provider dropdown since it has no RAG ingestion", async () => {render(<CreateVectorStore accessToken="test-token" />);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsx b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsxindex 8f24e47340c..2422e83355d 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsx@@ -175,6 +175,7 @@ const CreateVectorStore: React.FC<CreateVectorStoreProps> = ({ accessToken, onSusetIsCreating(true);const results: RAGIngestResponse[] = [];let vectorStoreId: string | undefined;+ let failure: { name: string; error: unknown } | undefined;try {// Ingest each document@@ -208,19 +209,35 @@ const CreateVectorStore: React.FC<CreateVectorStoreProps> = ({ accessToken, onSuconsole.error(`Error ingesting ${doc.name}:`, error);// Update document status to errorsetDocuments((prev) => prev.map((d) => (d.uid === doc.uid ? { ...d, status: "error" as const } : d)));- throw error; // Stop processing on first error+ failure = { name: doc.name, error };+ break;}}+ if (failure && !vectorStoreId) {+ throw failure.error;+ }+setIngestResults(results);- toast.success(- `Successfully created vector store with ${results.length} document(s). Vector Store ID: ${vectorStoreId}`,- );+ if (failure) {+ toast.warning(+ `Vector store ${vectorStoreId} was created with ${results.length} document(s), but ${failure.name} failed to ingest`,+ { description: failure.error instanceof Error ? failure.error.message : String(failure.error) },+ );+ } else {+ toast.success(+ `Successfully created vector store with ${results.length} document(s). Vector Store ID: ${vectorStoreId}`,+ );+ }if (onSuccess && vectorStoreId) {onSuccess(vectorStoreId);}+ if (failure) {+ return;+ }+// Clear documents after successful creationsetTimeout(() => {setDocuments([]);diff --git a/ui/litellm-dashboard/src/components/networking.test.ts b/ui/litellm-dashboard/src/components/networking.test.tsindex dc582da6833..e7a55870345 100644--- a/ui/litellm-dashboard/src/components/networking.test.ts+++ b/ui/litellm-dashboard/src/components/networking.test.ts@@ -975,6 +975,30 @@ describe("modelCostMap", () => {});});+describe("ragIngestCall", () => {+ let currentFetch: typeof global.fetch;++ beforeEach(() => {+ currentFetch = global.fetch;+ });++ afterEach(() => {+ global.fetch = currentFetch;+ });++ it("rejects with the proxy's error text when the detail is an object", async () => {+ const reason = "Error code: 404 - No vector store found with id 'vs_missing'";+ global.fetch = vi.fn().mockResolvedValue({+ ok: false,+ json: async () => ({ detail: { error: reason } }),+ } as any) as any;++ await expect(+ Networking.ragIngestCall("sk-test", new File(["text"], "doc.txt"), "openai", "vs_missing"),+ ).rejects.toThrow(reason);+ });+});+describe("getUiConfig runtime backend discovery", () => {const discoveryConfig = () => ({server_root_path: "/",diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 0f7d76a7156..4df34275923 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -5786,7 +5786,7 @@ export const ragIngestCall = async (if (!response.ok) {const error = await response.json();- throw new Error(error.error?.message || error.detail || "Failed to ingest document");+ throw new Error(deriveErrorMessage(error));}return await response.json();