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
Merge litellm_internal_staging (4c3ef9ae0a) into litellm_fix_s3_vectors_search
mateo-berri753f3705d07d
diff --cc litellm/llms/azure_ai/vector_stores/transformation.pyindex bd3eaeee989,5e61d0a1dd9..64e72b819b1--- a/litellm/llms/azure_ai/vector_stores/transformation.py+++ b/litellm/llms/azure_ai/vector_stores/transformation.py@@@ -92,9 -114,8 +115,9 @@@ class AzureAIVectorStoreConfig(BaseVectapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict[str, Any]]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict[str, Any]]:"""Transform search request for Azure AI Search APIdiff --cc litellm/llms/base_llm/vector_store/transformation.pyindex 9a0e401b527,02a51a8bace..63e99c0915a--- a/litellm/llms/base_llm/vector_store/transformation.py+++ b/litellm/llms/base_llm/vector_store/transformation.py@@@ -56,9 -56,8 +57,9 @@@ class BaseVectorStoreConfigapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:passasync def atransform_search_vector_store_request(@@@ -69,9 -68,8 +70,9 @@@api_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:"""Optional async version of transform_search_vector_store_request.If not implemented, the handler will fall back to the sync version.@@@ -158,5 -153,77 +157,78 @@@def calculate_vector_store_cost(self,response: VectorStoreSearchResponse,- ) -> Tuple[float, float]:+ ) -> tuple[float, float]:return 0.0, 0.0+++ class BaseDirectVectorStoreConfig(BaseVectorStoreConfig):+ """+ Base config for vector store providers whose datastore has no HTTP API+ (e.g. Valkey over RESP). Instead of transforming to an httpx request, the+ config executes the search itself via (a)execute_search_vector_store_request.+ """++ @abstractmethod+ def execute_search_vector_store_request(+ self,+ vector_store_id: str,+ query: str | Sequence[str],+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,+ litellm_logging_obj: LiteLLMLoggingObj,+ litellm_params: Mapping[str, object],+ timeout: float | httpx.Timeout | None = None,+ ) -> VectorStoreSearchResponse:+ pass++ @abstractmethod+ async def aexecute_search_vector_store_request(+ self,+ vector_store_id: str,+ query: str | Sequence[str],+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,+ litellm_logging_obj: LiteLLMLoggingObj,+ litellm_params: Mapping[str, object],+ timeout: float | httpx.Timeout | None = None,+ ) -> VectorStoreSearchResponse:+ pass++ def transform_search_vector_store_request(+ self,+ vector_store_id: str,+ query: str | Sequence[str],+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,+ api_base: str,+ litellm_logging_obj: LiteLLMLoggingObj,+ litellm_params: Mapping[str, object],+ extra_body: Mapping[str, object] | None = None,++ router: "Router | None" = None,+ ) -> NoReturn:+ raise NotImplementedError("Direct vector store providers execute the search themselves; no HTTP request shape")++ def transform_search_vector_store_response(+ self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj+ ) -> NoReturn:+ raise NotImplementedError("Direct vector store providers execute the search themselves; no HTTP response shape")++ def transform_create_vector_store_request(+ self,+ vector_store_create_optional_params: VectorStoreCreateOptionalRequestParams,+ api_base: str,+ ) -> NoReturn:+ raise NotImplementedError++ def transform_create_vector_store_response(self, response: httpx.Response) -> NoReturn:+ raise NotImplementedError++ def get_complete_url(+ self,+ api_base: str | None,+ litellm_params: Mapping[str, object],+ ) -> str:+ return api_base or ""++ def get_auth_credentials(self, litellm_params: Mapping[str, object]) -> BaseVectorStoreAuthCredentials:+ return BaseVectorStoreAuthCredentials()++ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints:+ return VectorStoreIndexEndpoints(read=[], write=[]) # mutable-ok: the TypedDict declares list fieldsdiff --cc litellm/llms/bedrock/vector_stores/transformation.pyindex 7a6a0eb6d84,2d72db0cdba..bad17a2181d--- a/litellm/llms/bedrock/vector_stores/transformation.py+++ b/litellm/llms/bedrock/vector_stores/transformation.py@@@ -196,9 -195,8 +196,9 @@@ class BedrockVectorStoreConfig(BaseVectapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:if isinstance(query, list):query = " ".join(query)diff --cc litellm/llms/custom_httpx/llm_http_handler.pyindex ec701fbe87e,834f7d564a2..6f42d42de00--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@@ -2814,10 -2920,10 +2921,10 @@@ class BaseLLMHTTPHandlerlogging_obj=logging_obj,)- final_response = await self._call_agentic_completion_hooks(+ final_response: Final = await self._call_agentic_completion_hooks(response=initial_response,model=model,-- messages=(input if isinstance(input, list) else [{"role": "user", "content": input}]),++ messages=(input if isinstance(input, list) else [{"role": "user", "content": input}]), # pyright: ignore[reportArgumentType] # pre-existing mismatch surfaced by the Router import; the hook accepts response input items at runtimeanthropic_messages_provider_config=responses_api_provider_config,anthropic_messages_optional_request_params=response_api_optional_request_params,logging_obj=logging_obj,@@@ -5193,9 -5413,9 +5414,9 @@@kwargs_for_followup["_agentic_loop_fingerprints"] = fingerprints + [fingerprint]try:- response = await litellm.aresponses(+ response: ResponsesAPIResponse | BaseResponsesAPIStreamingIterator = await litellm.aresponses(model=patch.model or model,-- input=patch.messages,++ input=patch.messages, # pyright: ignore[reportArgumentType] # pre-existing mismatch surfaced by the Router import; patch messages are valid response input at runtime**optional_params,**kwargs_for_followup,)@@@ -9405,13 -9683,28 +9684,29 @@@custom_llm_provider: str,litellm_params: GenericLiteLLMParams,logging_obj: LiteLLMLoggingObj,- extra_headers: Optional[Dict[str, Any]] = None,- extra_body: Optional[Dict[str, Any]] = None,- timeout: Optional[Union[float, httpx.Timeout]] = None,- client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ extra_headers: dict[str, object] | None = None,+ extra_body: dict[str, object] | None = None,+ timeout: float | httpx.Timeout | None = None,+ client: HTTPHandler | AsyncHTTPHandler | None = None,_is_async: bool = False,- router: Optional["Router"] = None,++ router: "Router | None" = None,) -> VectorStoreSearchResponse:+ if isinstance(vector_store_provider_config, BaseDirectVectorStoreConfig):+ self._pre_call_direct_vector_store_search(+ logging_obj=logging_obj,+ custom_llm_provider=custom_llm_provider,+ vector_store_id=vector_store_id,+ query=query,+ )+ return await vector_store_provider_config.aexecute_search_vector_store_request(+ vector_store_id=vector_store_id,+ query=query,+ vector_store_search_optional_params=vector_store_search_optional_params,+ litellm_logging_obj=logging_obj,+ litellm_params=dict(litellm_params), # mutable-ok: snapshot GenericLiteLLMParams into the Mapping shape+ timeout=timeout,+ )+if client is None or not isinstance(client, AsyncHTTPHandler):async_httpx_client = get_async_httpx_client(llm_provider=litellm.LlmProviders(custom_llm_provider),@@@ -9459,9 -9751,8 +9754,9 @@@litellm_logging_obj=logging_obj,litellm_params=dict(litellm_params),extra_body=extra_body,+ router=router,)- all_optional_params: Dict[str, Any] = dict(litellm_params)+ all_optional_params: Final[dict[str, object]] = dict(litellm_params)all_optional_params.update(vector_store_search_optional_params or {})headers, signed_json_body = vector_store_provider_config.sign_request(headers=headers,@@@ -9506,13 -9797,12 +9801,13 @@@custom_llm_provider: str,litellm_params: GenericLiteLLMParams,logging_obj: LiteLLMLoggingObj,- extra_headers: Optional[Dict[str, Any]] = None,- extra_body: Optional[Dict[str, Any]] = None,- timeout: Optional[Union[float, httpx.Timeout]] = None,- client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ extra_headers: dict[str, object] | None = None,+ extra_body: dict[str, object] | None = None,+ timeout: float | httpx.Timeout | None = None,+ client: HTTPHandler | AsyncHTTPHandler | None = None,_is_async: bool = False,- router: Optional["Router"] = None,- ) -> Union[VectorStoreSearchResponse, Coroutine[Any, Any, VectorStoreSearchResponse]]:++ router: "Router | None" = None,+ ) -> VectorStoreSearchResponse | Coroutine[object, object, VectorStoreSearchResponse]:if _is_async:return self.async_vector_store_search_handler(vector_store_id=vector_store_id,@@@ -9526,9 -9816,24 +9821,25 @@@extra_body=extra_body,timeout=timeout,client=client,+ router=router,)+ if isinstance(vector_store_provider_config, BaseDirectVectorStoreConfig):+ self._pre_call_direct_vector_store_search(+ logging_obj=logging_obj,+ custom_llm_provider=custom_llm_provider,+ vector_store_id=vector_store_id,+ query=query,+ )+ return vector_store_provider_config.execute_search_vector_store_request(+ vector_store_id=vector_store_id,+ query=query,+ vector_store_search_optional_params=vector_store_search_optional_params,+ litellm_logging_obj=logging_obj,+ litellm_params=dict(litellm_params), # mutable-ok: snapshot GenericLiteLLMParams into the Mapping shape+ timeout=timeout,+ )+if client is None or not isinstance(client, HTTPHandler):sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)})else:@@@ -9557,10 -9862,9 +9868,10 @@@litellm_logging_obj=logging_obj,litellm_params=dict(litellm_params),extra_body=extra_body,+ router=router,)- all_optional_params: Dict[str, Any] = dict(litellm_params)+ all_optional_params: Final[dict[str, object]] = dict(litellm_params)all_optional_params.update(vector_store_search_optional_params or {})headers, signed_json_body = vector_store_provider_config.sign_request(diff --cc litellm/llms/gemini/vector_stores/transformation.pyindex 5aba5752a44,f6525a449b6..82586b1f638--- a/litellm/llms/gemini/vector_stores/transformation.py+++ b/litellm/llms/gemini/vector_stores/transformation.py@@@ -111,9 -167,8 +168,9 @@@ class GeminiVectorStoreConfig(BaseVectoapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:+ extra_body: Mapping[str, object] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:"""Transform search request to Gemini's generateContent format.diff --cc litellm/llms/milvus/vector_stores/transformation.pyindex 589063cd188,34f0cd854c4..c3581abfbcc--- a/litellm/llms/milvus/vector_stores/transformation.py+++ b/litellm/llms/milvus/vector_stores/transformation.py@@@ -123,9 -122,8 +123,9 @@@ class MilvusVectorStoreConfig(BaseVectoapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict[str, Any]]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict[str, Any]]:"""Transform search request for Azure AI Search APIdiff --cc litellm/llms/openai/vector_stores/transformation.pyindex 9ab1568a375,f6c093f2e2a..4e925494039--- a/litellm/llms/openai/vector_stores/transformation.py+++ b/litellm/llms/openai/vector_stores/transformation.py@@@ -99,12 -98,11 +99,12 @@@ class OpenAIVectorStoreConfig(BaseVectoapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:- encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id")- url = f"{api_base}/{encoded_vector_store_id}/search"- typed_request_body = VectorStoreSearchRequest(+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:+ encoded_vector_store_id: Final = encode_url_path_segment(vector_store_id, field_name="vector_store_id")+ url: Final = f"{api_base}/{encoded_vector_store_id}/search"+ typed_request_body: Final = VectorStoreSearchRequest(query=query,filters=vector_store_search_optional_params.get("filters", None),max_num_results=vector_store_search_optional_params.get("max_num_results", None),diff --cc litellm/llms/pg_vector/vector_stores/transformation.pyindex 116f79c834f,e4b06c36bf4..9de1f589ae4--- a/litellm/llms/pg_vector/vector_stores/transformation.py+++ b/litellm/llms/pg_vector/vector_stores/transformation.py@@@ -80,11 -79,10 +80,11 @@@ class PGVectorStoreConfig(OpenAIVectorSapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:- encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id")- url = f"{api_base}/{encoded_vector_store_id}/search"+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:+ encoded_vector_store_id: Final = encode_url_path_segment(vector_store_id, field_name="vector_store_id")+ url: Final = f"{api_base}/{encoded_vector_store_id}/search"_, request_body = super().transform_search_vector_store_request(vector_store_id=vector_store_id,query=query,diff --cc litellm/llms/ragflow/vector_stores/transformation.pyindex 332ed7f0c6b,282cb7a92a7..ffa6c9e1076--- a/litellm/llms/ragflow/vector_stores/transformation.py+++ b/litellm/llms/ragflow/vector_stores/transformation.py@@@ -92,9 -91,8 +92,9 @@@ class RAGFlowVectorStoreConfig(BaseVectapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:"""RAGFlow vector stores are management-only, search is not supported."""raise NotImplementedError("RAGFlow vector stores support dataset management only, not search/retrieval")diff --cc litellm/llms/s3_vectors/vector_stores/transformation.pyindex a999db21dbe,5be35ae4148..3c1b0025d08--- a/litellm/llms/s3_vectors/vector_stores/transformation.py+++ b/litellm/llms/s3_vectors/vector_stores/transformation.py@@@ -1,4 -1,5 +1,4 @@@- from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union-import re+ from typing import TYPE_CHECKING, Any, Finalimport httpx@@@ -58,19 -57,14 +58,19 @@@ class S3VectorsVectorStoreConfig(BaseVeheaders.setdefault("Content-Type", "application/json")return headers- def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str:+ def get_complete_url(self, api_base: str | None, litellm_params: dict) -> str:- aws_region_name: Final = litellm_params.get("aws_region_name")- if not aws_region_name:- raise ValueError("aws_region_name is required for S3 Vectors")- if not re.match(r"^[a-z][a-z0-9-]*$", aws_region_name):- raise ValueError("Invalid aws_region_name format")+ # Resolve region the same way the ingestion path does:+ # dynamic param -> AWS_REGION_NAME -> AWS_REGION -> default (us-west-2)- aws_region_name = self.get_aws_region_name_for_non_llm_api_calls(litellm_params.get("aws_region_name"))++ aws_region_name: Final = self.get_aws_region_name_for_non_llm_api_calls(litellm_params.get("aws_region_name"))return f"https://s3vectors.{aws_region_name}.api.aws"- def _resolve_query_embedding_router(self, embedding_model: str, router: Optional["Router"]) -> Optional["Router"]:++ def _resolve_query_embedding_router(self, embedding_model: str, router: "Router | None") -> "Router | None":+ """Return the router iff it serves ``embedding_model`` as a deployment."""+ if router is None:+ return None- model_list = [dict(m) for m in (router.get_model_list() or [])]++ model_list: Final = [dict(m) for m in (router.get_model_list() or ())] # mutable-ok: resolve_embedding_router requires list[dict]+ return resolve_embedding_router(embedding_model=embedding_model, llm_router=router, llm_model_list=model_list)+def transform_search_vector_store_request(self,vector_store_id: str,@@@ -79,9 -73,8 +79,9 @@@api_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:"""Sync version - generates embedding synchronously."""# For S3 Vectors, vector_store_id should be in format: bucket_name:index_name# If not in that format, try to construct it from litellm_params@@@ -105,20 -98,16 +105,22 @@@query = " ".join(query)# Generate embedding for the query- embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small")- embedding_router = self._resolve_query_embedding_router(embedding_model=embedding_model, router=router)+ embedding_model: Final = litellm_params.get("embedding_model", "text-embedding-3-small")++ embedding_router: Final = self._resolve_query_embedding_router(embedding_model=embedding_model, router=router)import litellm as litellm_module- if embedding_router is not None:- embedding_response = embedding_router.embedding(model=embedding_model, input=[query])- else:- embedding_response = litellm_module.embedding(model=embedding_model, input=[query])- query_embedding = embedding_response.data[0]["embedding"]- embedding_response: Final = litellm_module.embedding(model=embedding_model, input=[query])++ embedding_input: Final = [query] # mutable-ok: the embedding API takes list input++ embedding_response: Final = (++ embedding_router.embedding(model=embedding_model, input=embedding_input)++ if embedding_router is not None++ else litellm_module.embedding(model=embedding_model, input=embedding_input)++ )+ query_embedding: Final = embedding_response.data[0]["embedding"]- url = f"{api_base}/QueryVectors"+ url: Final = f"{api_base}/QueryVectors"- request_body: Dict[str, Any] = {+ request_body: Final[dict[str, Any]] = {"vectorBucketName": bucket_name,"indexName": index_name,"queryVector": {"float32": query_embedding},@@@ -138,9 -127,8 +140,9 @@@api_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict]:+ extra_body: dict[str, Any] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict]:"""Async version - generates embedding asynchronously."""# For S3 Vectors, vector_store_id should be in format: bucket_name:index_name# If not in that format, try to construct it from litellm_params@@@ -164,20 -152,16 +166,22 @@@query = " ".join(query)# Generate embedding for the query asynchronously- embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small")- embedding_router = self._resolve_query_embedding_router(embedding_model=embedding_model, router=router)+ embedding_model: Final = litellm_params.get("embedding_model", "text-embedding-3-small")++ embedding_router: Final = self._resolve_query_embedding_router(embedding_model=embedding_model, router=router)import litellm as litellm_module- if embedding_router is not None:- embedding_response = await embedding_router.aembedding(model=embedding_model, input=[query])- else:- embedding_response = await litellm_module.aembedding(model=embedding_model, input=[query])- query_embedding = embedding_response.data[0]["embedding"]- embedding_response: Final = await litellm_module.aembedding(model=embedding_model, input=[query])++ embedding_input: Final = [query] # mutable-ok: the embedding API takes list input++ embedding_response: Final = (++ await embedding_router.aembedding(model=embedding_model, input=embedding_input)++ if embedding_router is not None++ else await litellm_module.aembedding(model=embedding_model, input=embedding_input)++ )+ query_embedding: Final = embedding_response.data[0]["embedding"]- url = f"{api_base}/QueryVectors"+ url: Final = f"{api_base}/QueryVectors"- request_body: Dict[str, Any] = {+ request_body: Final[dict[str, Any]] = {"vectorBucketName": bucket_name,"indexName": index_name,"queryVector": {"float32": query_embedding},diff --cc litellm/llms/vertex_ai/vector_stores/rag_api/transformation.pyindex 93ad40616b5,5c250fc1a7e..36b57e7c995--- a/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py+++ b/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py@@@ -97,9 -160,8 +161,9 @@@ class VertexVectorStoreConfig(BaseVectoapi_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict[str, Any]]:+ extra_body: Mapping[str, object] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict[str, object]]:"""Transform search request for Vertex AI RAG API"""diff --cc litellm/llms/vertex_ai/vector_stores/search_api/transformation.pyindex f6f9e34dc75,0bcf16ee06f..f0812e3ed9f--- a/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py+++ b/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py@@@ -197,9 -244,8 +245,9 @@@ class VertexSearchAPIVectorStoreConfig(api_base: str,litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,- extra_body: Optional[Dict[str, Any]] = None,- router: Optional["Router"] = None,- ) -> Tuple[str, Dict[str, Any]]:+ extra_body: Mapping[str, object] | None = None,++ router: "Router | None" = None,+ ) -> tuple[str, dict[str, object]]:"""Transform a search request for the Vertex AI Search (Discovery Engine) API.diff --cc litellm/proxy/rag_endpoints/endpoints.pyindex 0d93f20373c,db574f859b3..31998d2040e--- a/litellm/proxy/rag_endpoints/endpoints.py+++ b/litellm/proxy/rag_endpoints/endpoints.py@@@ -26,9 -29,13 +29,16 @@@ from litellm.proxy.common_utils.http_pa_safe_get_request_headers,get_form_data,)+ from litellm.proxy.rag_endpoints.upload_security import (+ MAX_UPLOAD_SIZE_BYTES,+ EicarTestMalwareScanner,+ MalwareScanner,+ RejectedUpload,+ validate_upload,+ )+from litellm.proxy.vector_store_endpoints.endpoints import (- _update_request_data_with_litellm_managed_vector_store_registry,++ _update_request_data_with_litellm_managed_vector_store_registry, # pyright: ignore[reportPrivateUsage] # shared registry-merge helper used by the direct search endpoint+)from litellm.proxy.vector_store_endpoints.utils import (assert_user_can_access_vector_store_id,)@@@ -655,19 -705,8 +708,19 @@@ async def rag_queryuser_api_key_dict=user_api_key_dict,)+ # Merge litellm-managed vector store params (provider, region, embedding+ # model, credentials, ...) from the registry — same source the direct+ # /vector_stores/{id}/search endpoint uses. User-supplied+ # retrieval_config keys win on conflict.- store_data = await _update_request_data_with_litellm_managed_vector_store_registry(- data={},++ store_data: Final = await _update_request_data_with_litellm_managed_vector_store_registry(++ data={}, # mutable-ok: the helper mutates and returns the seed dict+ vector_store_id=retrieval_config["vector_store_id"],+ user_api_key_dict=user_api_key_dict,+ )- retrieval_config = {**store_data, **retrieval_config}++ merged_retrieval_config: Final = {**store_data, **retrieval_config} # mutable-ok: litellm.aquery requires a plain dict payload+# Add litellm data- request_data: Dict[str, Any] = {}+ request_data: dict[str, object] = {}request_data = await add_litellm_data_to_request(data=request_data,request=request,@@@ -677,13 -716,13 +730,13 @@@proxy_config=proxy_config,)- verbose_proxy_logger.debug(f"RAG Query - model: {model}, retrieval_config: {retrieval_config}")- verbose_proxy_logger.debug("RAG Query - model: %s, retrieval_config: %s", model, retrieval_config)++ verbose_proxy_logger.debug("RAG Query - model: %s, retrieval_config: %s", model, merged_retrieval_config)# Call query- response = await litellm.aquery(+ response: Final = await litellm.aquery(model=model,messages=messages,-- retrieval_config=retrieval_config,++ retrieval_config=merged_retrieval_config,rerank=rerank,stream=stream,router=llm_router,diff --cc litellm/rag/main.pyindex 2329a820f1f,2dcaa200cc6..2e940a1613a--- a/litellm/rag/main.py+++ b/litellm/rag/main.py@@@ -11,20 -11,10 +11,11 @@@ __all__ = ["aingest", "aquery", "ingestimport asyncioimport contextvars+ from collections.abc import Coroutine, Iteratorfrom contextlib import contextmanagerfrom functools import partial- from typing import (- TYPE_CHECKING,- Any,- Coroutine,- Dict,- Iterator,- List,- Optional,- Tuple,- Type,- Union,- )++from types import MappingProxyType+ from typing import TYPE_CHECKING, Any, Finalimport httpx@@@ -59,16 -49,8 +50,16 @@@ INGESTION_REGISTRY: Final[dict[str, typ"vertex_ai": VertexAIRAGIngestion,}+# retrieval_config keys consumed by the query pipeline itself; everything else is+# forwarded to vector_stores.asearch as provider-specific params (e.g.+# aws_region_name, embedding_model, vector_bucket_name for S3 Vectors).+# `filters`/`retrieval_filter` are reserved for the explicit filter param.- _CONSUMED_RETRIEVAL_CONFIG_KEYS = frozenset(++_CONSUMED_RETRIEVAL_CONFIG_KEYS: Final = frozenset(+ {"vector_store_id", "custom_llm_provider", "top_k", "filters", "retrieval_filter"}+)+- def get_ingestion_class(provider: str) -> Type[BaseRAGIngestion]:+ def get_ingestion_class(provider: str) -> type[BaseRAGIngestion]:"""Get the ingestion class for a given provider.@@@ -241,20 -223,16 +232,23 @@@ async def _execute_query_pipelineraise ValueError("No query found in messages for RAG query")# 2. Search vector store+ # Forward provider-specific retrieval_config extras (region, embedding model,+ # bucket, credentials refs, ...) to the search call; kwargs win on conflict.- provider_search_params = {k: v for k, v in retrieval_config.items() if k not in _CONSUMED_RETRIEVAL_CONFIG_KEYS}++ provider_search_params: Final = MappingProxyType(++ {k: v for k, v in retrieval_config.items() if k not in _CONSUMED_RETRIEVAL_CONFIG_KEYS}++ )++ forwarded_search_params: Final = MappingProxyType({**provider_search_params, **kwargs})with _suppressed_sub_call_billing():- search_response = await litellm.vector_stores.asearch(+ search_response: Final = await litellm.vector_stores.asearch(vector_store_id=retrieval_config["vector_store_id"],query=query_text,max_num_results=retrieval_config.get("top_k", 10),custom_llm_provider=retrieval_config.get("custom_llm_provider", "openai"),- **kwargs,+ router=router,- **{**provider_search_params, **kwargs},++ **forwarded_search_params,)- search_provider = retrieval_config.get("custom_llm_provider", "openai")+ search_provider: Final = retrieval_config.get("custom_llm_provider", "openai")try:search_cost = sum(vector_store_search_cost(diff --cc litellm/router.pyindex bffd1df3814,edff8294c3e..d8769525815--- a/litellm/router.py+++ b/litellm/router.py@@@ -1918,8 -2318,8 +2318,8 @@@ class Router@overloadasync def acompletion(- self, model: str, messages: List[AllMessageValues], stream: Union[Literal[True], Literal[False]] = False, **kwargs- ) -> Union[CustomStreamWrapper, ModelResponse]:+ self, model: str, messages: list[AllMessageValues], stream: Literal[True, False] = False, **kwargs- ) -> CustomStreamWrapper | ModelResponse:++ ) -> CustomStreamWrapper | ModelResponse:...# fmt: on@@@ -5860,8 -6554,7 +6555,8 @@@async def _init_vector_store_api_endpoints(self,original_function: Callable,- custom_llm_provider: Optional[str] = None,- call_type: Optional[str] = None,+ custom_llm_provider: str | None = None,++ call_type: str | None = None,**kwargs,):"""@@@ -5880,12 -6573,6 +6575,13 @@@**kwargs,)+ # For search, pass the router so provider transforms can resolve+ # router-managed embedding models (e.g. S3 Vectors query embeddings).- # Assigning into kwargs also overrides any client-supplied `router` key.++ # The merge also overrides any client-supplied `router` key.+ if call_type == "avector_store_search":- kwargs["router"] = self++ search_kwargs: Final = MappingProxyType({**kwargs, "router": self})++ return await original_function(**search_kwargs)+# Otherwise, call the original function directlyreturn await original_function(**kwargs)diff --cc litellm/vector_stores/main.pyindex 4035125120e,9b0ff71730a..cd576755f5f--- a/litellm/vector_stores/main.py+++ b/litellm/vector_stores/main.py@@@ -5,8 -5,9 +5,9 @@@ LiteLLM SDK Functions for Creating andimport asyncioimport builtinsimport contextvars+ from collections.abc import Coroutine, Mappingfrom functools import partial- from typing import TYPE_CHECKING, Any, Coroutine, Dict, List, Optional, Union-from typing import Final++from typing import TYPE_CHECKING, Finalimport httpx@@@ -269,20 -267,19 +270,20 @@@ def create@clientasync def asearch(vector_store_id: str,- query: Union[str, List[str]],- filters: Optional[Dict] = None,- max_num_results: Optional[int] = None,- ranking_options: Optional[Dict] = None,- rewrite_query: Optional[bool] = None,+ query: str | list[str],+ filters: dict | None = None,+ max_num_results: int | None = None,+ ranking_options: dict | None = None,+ rewrite_query: bool | None = None,# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.# The extra values given here take precedence over values defined on the client or passed to this method.- extra_headers: Optional[Dict[str, Any]] = None,- extra_query: Optional[Dict[str, Any]] = None,- extra_body: Optional[Dict[str, Any]] = None,- timeout: Optional[Union[float, httpx.Timeout]] = None,+ extra_headers: dict[str, object] | None = None,+ extra_query: dict[str, object] | None = None,+ extra_body: dict[str, object] | None = None,+ timeout: float | httpx.Timeout | None = None,# LiteLLM specific params,- custom_llm_provider: Optional[str] = None,- router: Optional["Router"] = None,+ custom_llm_provider: str | None = None,++ router: "Router | None" = None,**kwargs,) -> VectorStoreSearchResponse:"""@@@ -338,22 -334,21 +339,22 @@@@clientdef search(vector_store_id: str,- query: Union[str, List[str]],- filters: Optional[Dict] = None,- max_num_results: Optional[int] = None,- ranking_options: Optional[Dict] = None,- rewrite_query: Optional[bool] = None,+ query: str | list[str],+ filters: dict | None = None,+ max_num_results: int | None = None,+ ranking_options: dict | None = None,+ rewrite_query: bool | None = None,# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.# The extra values given here take precedence over values defined on the client or passed to this method.- extra_headers: Optional[Dict[str, Any]] = None,- extra_query: Optional[Dict[str, Any]] = None,- extra_body: Optional[Dict[str, Any]] = None,- timeout: Optional[Union[float, httpx.Timeout]] = None,+ extra_headers: dict[str, object] | None = None,+ extra_query: dict[str, object] | None = None,+ extra_body: dict[str, object] | None = None,+ timeout: float | httpx.Timeout | None = None,# LiteLLM specific params,- custom_llm_provider: Optional[str] = None,- router: Optional["Router"] = None,+ custom_llm_provider: str | None = None,++ router: "Router | None" = None,**kwargs,- ) -> Union[VectorStoreSearchResponse, Coroutine[Any, Any, VectorStoreSearchResponse]]:+ ) -> VectorStoreSearchResponse | Coroutine[object, object, VectorStoreSearchResponse]:"""Search a vector store for relevant chunks based on a query and file attributes filter.diff --cc tests/test_litellm/llms/s3_vectors/vector_stores/test_s3_vectors_transformation.pyindex 9389476bef4,7085e45cdc3..4b58d220623--- a/tests/test_litellm/llms/s3_vectors/vector_stores/test_s3_vectors_transformation.py+++ b/tests/test_litellm/llms/s3_vectors/vector_stores/test_s3_vectors_transformation.py@@@ -40,174 -28,19 +40,174 @@@ class TestS3VectorsVectorStoreConfigurl = config.get_complete_url(None, litellm_params)assert url == "https://s3vectors.us-west-2.api.aws"- def test_get_complete_url_missing_region(self):- """Test that missing region raises error"""+ def test_get_complete_url_missing_region(self, monkeypatch):+ """Missing region falls back to the default region (parity with ingestion)"""+ monkeypatch.delenv("AWS_REGION_NAME", raising=False)+ monkeypatch.delenv("AWS_REGION", raising=False)+ config = S3VectorsVectorStoreConfig()+ url = config.get_complete_url(None, {})+ assert url == "https://s3vectors.us-west-2.api.aws"++ def test_get_complete_url_uses_env_region(self, monkeypatch):+ """Missing region param resolves from AWS_REGION_NAME env var"""+ monkeypatch.setenv("AWS_REGION_NAME", "eu-west-1")+ monkeypatch.delenv("AWS_REGION", raising=False)config = S3VectorsVectorStoreConfig()- litellm_params = {}- with pytest.raises(ValueError, match="aws_region_name is required"):- config.get_complete_url(None, litellm_params)+ url = config.get_complete_url(None, {})+ assert url == "https://s3vectors.eu-west-1.api.aws"++ def test_get_complete_url_invalid_region_format(self):+ """Invalid region format raises"""+ config = S3VectorsVectorStoreConfig()+ with pytest.raises(ValueError, match="Invalid AWS region format"):+ config.get_complete_url(None, {"aws_region_name": "Bad_Region!"})- @pytest.mark.skip(reason="Requires embedding API call, tested in integration tests")def test_transform_search_request(self):- """Test search request transformation"""- # This test requires making an actual embedding API call- # It's better tested in integration tests- pass+ """Full request-body transformation with a router-injected embedding"""+ config = S3VectorsVectorStoreConfig()+ mock_logging_obj = Mock()+ mock_logging_obj.model_call_details = {}+ router = _mock_router(["text-embedding-3-small"], sync=True)++ url, request_body = config.transform_search_vector_store_request(+ vector_store_id="test-bucket:test-index",+ query="test query",+ vector_store_search_optional_params={"max_num_results": 7},+ api_base="https://s3vectors.us-west-2.api.aws",+ litellm_logging_obj=mock_logging_obj,+ litellm_params={},+ extra_body=None,+ router=router,+ )++ assert url == "https://s3vectors.us-west-2.api.aws/QueryVectors"+ assert request_body == {+ "vectorBucketName": "test-bucket",+ "indexName": "test-index",+ "queryVector": {"float32": [0.1, 0.2, 0.3]},+ "topK": 7,+ "returnDistance": True,+ "returnMetadata": True,+ }+ assert mock_logging_obj.model_call_details["query"] == "test query"++ @pytest.mark.asyncio+ async def test_atransform_search_uses_router_for_virtual_model(self):+ """Regression: router-served embedding models must resolve via the router,+ not a bare litellm.aembedding call (which has no deployment credentials)."""+ config = S3VectorsVectorStoreConfig()+ mock_logging_obj = Mock()+ mock_logging_obj.model_call_details = {}+ router = _mock_router(["my-embedding-model"])+- with patch("litellm.aembedding", new=AsyncMock()) as mock_bare_aembedding:++ with patch("litellm.aembedding", new=AsyncMock()) as mock_bare_aembedding: # test-quality-ok: guards that the bare-embedding path is not taken; dispatch seam is the behavior under test+ url, request_body = await config.atransform_search_vector_store_request(+ vector_store_id="test-bucket:test-index",+ query="test query",+ vector_store_search_optional_params={},+ api_base="https://s3vectors.us-west-2.api.aws",+ litellm_logging_obj=mock_logging_obj,+ litellm_params={"embedding_model": "my-embedding-model"},+ extra_body=None,+ router=router,+ )++ router.aembedding.assert_awaited_once_with(model="my-embedding-model", input=["test query"])+ mock_bare_aembedding.assert_not_awaited()+ assert request_body["queryVector"]["float32"] == [0.1, 0.2, 0.3]+ assert request_body["topK"] == 5 # default++ @pytest.mark.asyncio+ async def test_atransform_search_falls_back_when_router_does_not_serve_model(self):+ """Router present but embedding_model is not a router deployment ->+ bare litellm.aembedding keeps working (provider-prefixed + env creds stores)."""+ config = S3VectorsVectorStoreConfig()+ mock_logging_obj = Mock()+ mock_logging_obj.model_call_details = {}+ router = _mock_router(["some-other-model"])++ mock_bare = AsyncMock(return_value=Mock(data=[{"embedding": [0.4, 0.5]}]))- with patch("litellm.aembedding", new=mock_bare):++ with patch("litellm.aembedding", new=mock_bare): # test-quality-ok: stubs the bare-embedding fallback whose request body the test asserts on+ _, request_body = await config.atransform_search_vector_store_request(+ vector_store_id="test-bucket:test-index",+ query="test query",+ vector_store_search_optional_params={},+ api_base="https://s3vectors.us-west-2.api.aws",+ litellm_logging_obj=mock_logging_obj,+ litellm_params={"embedding_model": "azure/text-embedding-3-small"},+ extra_body=None,+ router=router,+ )++ mock_bare.assert_awaited_once_with(model="azure/text-embedding-3-small", input=["test query"])+ router.aembedding.assert_not_awaited()+ assert request_body["queryVector"]["float32"] == [0.4, 0.5]++ @pytest.mark.asyncio+ async def test_atransform_search_without_router_uses_bare_embedding(self):+ """Backward compat: no router -> bare litellm.aembedding as before"""+ config = S3VectorsVectorStoreConfig()+ mock_logging_obj = Mock()+ mock_logging_obj.model_call_details = {}++ mock_bare = AsyncMock(return_value=Mock(data=[{"embedding": [0.6, 0.7]}]))- with patch("litellm.aembedding", new=mock_bare):++ with patch("litellm.aembedding", new=mock_bare): # test-quality-ok: stubs the bare-embedding fallback whose request body the test asserts on+ _, request_body = await config.atransform_search_vector_store_request(+ vector_store_id="test-bucket:test-index",+ query="test query",+ vector_store_search_optional_params={},+ api_base="https://s3vectors.us-west-2.api.aws",+ litellm_logging_obj=mock_logging_obj,+ litellm_params={},+ extra_body=None,+ )++ mock_bare.assert_awaited_once_with(model="text-embedding-3-small", input=["test query"])+ assert request_body["queryVector"]["float32"] == [0.6, 0.7]++ def test_transform_search_uses_router_for_virtual_model_sync(self):+ """Sync twin: router-served embedding model resolves via router.embedding"""+ config = S3VectorsVectorStoreConfig()+ mock_logging_obj = Mock()+ mock_logging_obj.model_call_details = {}+ router = _mock_router(["my-embedding-model"], sync=True)+- with patch("litellm.embedding", new=MagicMock()) as mock_bare_embedding:++ with patch("litellm.embedding", new=MagicMock()) as mock_bare_embedding: # test-quality-ok: guards that the bare-embedding path is not taken; dispatch seam is the behavior under test+ _, request_body = config.transform_search_vector_store_request(+ vector_store_id="test-bucket:test-index",+ query="test query",+ vector_store_search_optional_params={},+ api_base="https://s3vectors.us-west-2.api.aws",+ litellm_logging_obj=mock_logging_obj,+ litellm_params={"embedding_model": "my-embedding-model"},+ extra_body=None,+ router=router,+ )++ router.embedding.assert_called_once_with(model="my-embedding-model", input=["test query"])+ mock_bare_embedding.assert_not_called()+ assert request_body["queryVector"]["float32"] == [0.1, 0.2, 0.3]++ def test_transform_search_without_router_uses_bare_embedding_sync(self):+ """Sync twin: no router -> bare litellm.embedding as before"""+ config = S3VectorsVectorStoreConfig()+ mock_logging_obj = Mock()+ mock_logging_obj.model_call_details = {}++ mock_bare = MagicMock(return_value=Mock(data=[{"embedding": [0.8, 0.9]}]))- with patch("litellm.embedding", new=mock_bare):++ with patch("litellm.embedding", new=mock_bare): # test-quality-ok: stubs the bare-embedding fallback whose request body the test asserts on+ _, request_body = config.transform_search_vector_store_request(+ vector_store_id="test-bucket:test-index",+ query="test query",+ vector_store_search_optional_params={},+ api_base="https://s3vectors.us-west-2.api.aws",+ litellm_logging_obj=mock_logging_obj,+ litellm_params={},+ extra_body=None,+ )++ mock_bare.assert_called_once_with(model="text-embedding-3-small", input=["test query"])+ assert request_body["queryVector"]["float32"] == [0.8, 0.9]def test_transform_search_request_invalid_vector_store_id(self):"""Test that invalid vector_store_id format raises error"""diff --cc tests/test_litellm/proxy/rag_endpoints/test_rag_endpoints.pyindex 8bd67754952,abbf6892a98..5561ee1e6ae--- a/tests/test_litellm/proxy/rag_endpoints/test_rag_endpoints.py+++ b/tests/test_litellm/proxy/rag_endpoints/test_rag_endpoints.py@@@ -329,104 -324,90 +324,191 @@@ def test_rag_query_stream_returns_eventassert "data: [DONE]" in response.text+def test_rag_query_merges_managed_store_params(client_internal_user):+ """+ Regression: /v1/rag/query must consult the managed vector store registry+ (like the direct /v1/vector_stores/{id}/search endpoint does) so that+ provider, region, embedding model, etc. don't have to be repeated in+ retrieval_config. Pre-fix the registry was never read, so managed S3+ Vectors stores failed with "aws_region_name is required".+ """+ import litellm+ from litellm.types.utils import ModelResponse++ mock_vector_store = {+ "vector_store_id": "s3-store",+ "custom_llm_provider": "s3_vectors",+ "litellm_params": {+ "aws_region_name": "eu-west-1",+ "embedding_model": "my-embed",+ "vector_bucket_name": "bkt",+ },+ }+ mock_registry = MagicMock()+ mock_registry.get_litellm_managed_vector_store_from_registry.return_value = mock_vector_store++ mock_response = ModelResponse(+ id="chatcmpl-test",+ choices=[{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],+ model="gpt-4o-mini",+ )+- with patch(++ 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(++ ) 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 stubs the access assert covered by auth tests+ "litellm.proxy.rag_endpoints.endpoints.assert_user_can_access_vector_store_id",+ new=AsyncMock(),- ), patch(++ ), patch( # test-quality-ok: stubs the direct-endpoint access assert covered by auth tests+ "litellm.proxy.vector_store_endpoints.endpoints.assert_user_can_access_vector_store",+ new=AsyncMock(),+ ):+ response = client_internal_user.post(+ "/v1/rag/query",+ json={+ "model": "gpt-4o-mini",+ "messages": [{"role": "user", "content": "hello"}],+ "retrieval_config": {"vector_store_id": "s3-store"},+ },+ )++ assert response.status_code == 200, response.json()+ mock_aquery.assert_awaited_once()+ forwarded_config = mock_aquery.await_args.kwargs["retrieval_config"]+ assert forwarded_config["vector_store_id"] == "s3-store"+ assert forwarded_config["custom_llm_provider"] == "s3_vectors"+ assert forwarded_config["aws_region_name"] == "eu-west-1"+ assert forwarded_config["embedding_model"] == "my-embed"+ assert forwarded_config["vector_bucket_name"] == "bkt"+++def test_rag_query_user_retrieval_config_wins_over_store(client_internal_user):+ """User-supplied retrieval_config keys must win over registry values."""+ import litellm+ from litellm.types.utils import ModelResponse++ mock_vector_store = {+ "vector_store_id": "s3-store",+ "custom_llm_provider": "s3_vectors",+ "litellm_params": {"aws_region_name": "eu-west-1"},+ }+ mock_registry = MagicMock()+ mock_registry.get_litellm_managed_vector_store_from_registry.return_value = mock_vector_store++ mock_response = ModelResponse(+ id="chatcmpl-test",+ choices=[{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],+ model="gpt-4o-mini",+ )+- with patch(++ 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(++ ) 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 stubs the access assert covered by auth tests+ "litellm.proxy.rag_endpoints.endpoints.assert_user_can_access_vector_store_id",+ new=AsyncMock(),- ), patch(++ ), patch( # test-quality-ok: stubs the direct-endpoint access assert covered by auth tests+ "litellm.proxy.vector_store_endpoints.endpoints.assert_user_can_access_vector_store",+ new=AsyncMock(),+ ):+ response = client_internal_user.post(+ "/v1/rag/query",+ json={+ "model": "gpt-4o-mini",+ "messages": [{"role": "user", "content": "hello"}],+ "retrieval_config": {"vector_store_id": "s3-store", "aws_region_name": "us-east-1"},+ },+ )++ assert response.status_code == 200, response.json()+ forwarded_config = mock_aquery.await_args.kwargs["retrieval_config"]+ assert forwarded_config["aws_region_name"] == "us-east-1"+ EICAR = r"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"+ INGEST_REQUEST = '{"ingest_options":{"vector_store":{"custom_llm_provider":"openai"}}}'+++ def _multipart_ingest_request(*, filename: str, content: bytes, content_type: str):+ from starlette.requests import Request++ boundary = "litellmuploadtestboundary"+ head = (+ f"--{boundary}\r\n"+ f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'+ f"Content-Type: {content_type}\r\n\r\n"+ ).encode()+ tail = (+ f"\r\n--{boundary}\r\n"+ f'Content-Disposition: form-data; name="request"\r\n\r\n'+ f"{INGEST_REQUEST}\r\n"+ f"--{boundary}--\r\n"+ ).encode()+ body = head + content + tail+ scope = {+ "type": "http",+ "method": "POST",+ "path": "/v1/rag/ingest",+ "headers": [+ (b"content-type", f"multipart/form-data; boundary={boundary}".encode()),+ (b"content-length", str(len(body)).encode()),+ ],+ "state": {},+ }++ async def receive():+ return {"type": "http.request", "body": body, "more_body": False}++ return Request(scope, receive)+++ class TestVectorStoreUploadControls:+ """End-to-end enforcement of pentest M4 upload controls on /v1/rag/ingest."""++ def test_eicar_upload_blocked_by_malware_scanner(self, client_internal_user):+ response = client_internal_user.post(+ "/v1/rag/ingest",+ files={"file": ("clean_name.txt", io.BytesIO(EICAR.encode()), "text/plain")},+ data={"request": INGEST_REQUEST},+ )+ assert response.status_code == 400, response.text+ assert response.json()["detail"]["reason"] == "malware_detected"++ def test_executable_upload_rejected(self, client_internal_user):+ elf = b"\x7fELF\x02\x01\x01\x00" + b"\x00" * 40+ response = client_internal_user.post(+ "/v1/rag/ingest",+ files={"file": ("doc.txt", io.BytesIO(elf), "text/plain")},+ data={"request": INGEST_REQUEST},+ )+ assert response.status_code == 400, response.text+ assert response.json()["detail"]["reason"] == "executable_not_allowed"++ def test_zip_archive_upload_rejected(self, client_internal_user):+ response = client_internal_user.post(+ "/v1/rag/ingest",+ files={"file": ("doc.pdf", io.BytesIO(b"PK\x03\x04\x14\x00\x00\x00payload"), "application/pdf")},+ data={"request": INGEST_REQUEST},+ )+ assert response.status_code == 400, response.text+ assert response.json()["detail"]["reason"] == "archive_not_allowed"++ async def test_clean_text_upload_gets_server_generated_filename(self):+ from litellm.proxy.rag_endpoints.endpoints import parse_rag_ingest_request+ from litellm.proxy.rag_endpoints.upload_security import EicarTestMalwareScanner++ request = _multipart_ingest_request(+ filename="../../etc/passwd",+ content=b"benign document text\n",+ content_type="text/plain",+ )+ _options, file_data, _url, _file_id = await parse_rag_ingest_request(+ request, scanner=EicarTestMalwareScanner()+ )+ assert file_data is not None+ server_filename, content_bytes, secured_content_type = file_data+ assert server_filename != "../../etc/passwd"+ assert "/" not in server_filename and "\\" not in server_filename+ assert server_filename.endswith(".txt")+ assert secured_content_type == "text/plain"+ assert content_bytes == b"benign document text\n"diff --cc tests/test_litellm/rag/test_main.pyindex d8ffae667b1,2d1b460513f..fdcdf342eea--- a/tests/test_litellm/rag/test_main.py+++ b/tests/test_litellm/rag/test_main.py@@@ -254,96 -259,6 +259,96 @@@ async def test_aquery_streaming_bills_sassert standard_logging_object["response_cost"] >= 0.003+async def test_aquery_forwards_provider_retrieval_config_and_router_to_search():+ """+ Regression: provider-specific retrieval_config keys (aws_region_name,+ embedding_model, vector_bucket_name, ...) and the router must be forwarded+ to the vector store search call. Pre-fix they were silently dropped, so+ /v1/rag/query failed with provider config errors (e.g. S3 Vectors+ "aws_region_name is required") even when the caller supplied them.+ """+ from unittest.mock import AsyncMock++ from litellm.types.vector_stores import VectorStoreSearchResponse++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4o-mini",+ "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "test-key"},+ }+ ]+ )++ fake_search = AsyncMock(+ return_value=VectorStoreSearchResponse(+ object="vector_store.search_results.page", search_query="q", data=[]+ )+ )- with patch("litellm.vector_stores.asearch", new=fake_search):++ with patch("litellm.vector_stores.asearch", new=fake_search): # test-quality-ok: asearch is the boundary the forwarding contract under test targets+ response = await litellm.aquery(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hello"}],+ retrieval_config={+ "vector_store_id": "bkt:idx",+ "custom_llm_provider": "s3_vectors",+ "top_k": 5,+ "aws_region_name": "eu-west-1",+ "embedding_model": "my-embed",+ "vector_bucket_name": "bkt",+ },+ router=router,+ mock_response="hi",+ )++ assert isinstance(response, ModelResponse)+ fake_search.assert_awaited_once()+ search_kwargs = fake_search.await_args.kwargs+ assert search_kwargs["vector_store_id"] == "bkt:idx"+ assert search_kwargs["custom_llm_provider"] == "s3_vectors"+ assert search_kwargs["max_num_results"] == 5+ assert search_kwargs["router"] is router+ # provider-specific extras forwarded+ assert search_kwargs["aws_region_name"] == "eu-west-1"+ assert search_kwargs["embedding_model"] == "my-embed"+ assert search_kwargs["vector_bucket_name"] == "bkt"+ # consumed keys are not duplicated into the spread+ assert "top_k" not in search_kwargs+++async def test_aquery_minimal_retrieval_config_forwards_no_extras():+ """+ A minimal retrieval_config must not leak consumed keys (or invent extras)+ into the vector store search call.+ """+ from unittest.mock import AsyncMock++ from litellm.types.vector_stores import VectorStoreSearchResponse++ fake_search = AsyncMock(+ return_value=VectorStoreSearchResponse(+ object="vector_store.search_results.page", search_query="q", data=[]+ )+ )- with patch("litellm.vector_stores.asearch", new=fake_search):++ with patch("litellm.vector_stores.asearch", new=fake_search): # test-quality-ok: asearch is the boundary the forwarding contract under test targets+ await litellm.aquery(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hello"}],+ retrieval_config={"vector_store_id": "vs_test_123", "custom_llm_provider": "openai"},+ mock_response="hi",+ )++ fake_search.assert_awaited_once()+ search_kwargs = fake_search.await_args.kwargs+ assert search_kwargs["vector_store_id"] == "vs_test_123"+ assert search_kwargs["custom_llm_provider"] == "openai"+ assert search_kwargs["router"] is None+ leaked = {"top_k", "filters", "retrieval_filter", "aws_region_name", "embedding_model", "vector_bucket_name"}+ assert not (leaked & set(search_kwargs.keys()))++def test_rag_call_types_are_registered():"""query/aquery/ingest/aingest are @client-decorated entry points, so theirdiff --cc tests/test_litellm/test_router.pyindex 91d2973af76,44c1cdbff06..c222fab79f0--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@@ -5938,56 -7510,4088 +7510,4145 @@@ async def test_acreate_batch_request_beassert mock_sign.call_args.kwargs["data"]["tags"] == request_tags+async def test_avector_store_search_injects_router():+ """+ Regression: router.avector_store_search must pass the router down to the+ SDK search call so provider transforms can resolve router-managed+ embedding models (e.g. S3 Vectors query embeddings).+ """+ from litellm.types.vector_stores import VectorStoreSearchResponse+- mock_asearch = AsyncMock(- return_value=VectorStoreSearchResponse(- object="vector_store.search_results.page", search_query="q", data=[]- )++ expected_response = VectorStoreSearchResponse(++ object="vector_store.search_results.page", search_query="q", data=[]+ )++ mock_asearch = AsyncMock(return_value=expected_response)+ # Router.__init__ binds asearch via a local import, so patch the module+ # attribute before constructing the Router.- with patch("litellm.vector_stores.main.asearch", new=mock_asearch):++ with patch("litellm.vector_stores.main.asearch", new=mock_asearch): # test-quality-ok: the SDK call is the only place the injected router kwarg is observable+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "openai/gpt-3.5-turbo", "api_key": "test-key"},+ }+ ]+ )- await router.avector_store_search(++ search_response = await router.avector_store_search(+ vector_store_id="v", query="q", custom_llm_provider="s3_vectors"+ )+++ assert search_response is expected_response+ mock_asearch.assert_awaited_once()+ assert mock_asearch.await_args.kwargs["router"] is router+++async def test_avector_store_create_does_not_inject_router():+ """The router injection is gated on the search call type: the create path+ must keep calling the SDK without a router kwarg."""- mock_acreate = AsyncMock(return_value={"id": "vs_1", "object": "vector_store"})++ expected_response = {"id": "vs_1", "object": "vector_store"}++ mock_acreate = AsyncMock(return_value=expected_response)+ # avector_store_create(model=None) resolves acreate via a local import at+ # call time, so patching after Router construction works here.+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "openai/gpt-3.5-turbo", "api_key": "test-key"},+ }+ ]+ )- with patch("litellm.vector_stores.main.acreate", new=mock_acreate):- await router.avector_store_create(model=None, custom_llm_provider="openai")++ with patch("litellm.vector_stores.main.acreate", new=mock_acreate): # test-quality-ok: the SDK call is the only place a leaked router kwarg would surface++ create_response = await router.avector_store_create(model=None, custom_llm_provider="openai")+++ assert create_response is expected_response+ mock_acreate.assert_awaited_once()+ assert "router" not in mock_acreate.await_args.kwargs+++++ class TestPreRoutingStrategyRegistryLifecycle:+ """+ Regression tests: a deployment leaving the model_list must release the+ pre-routing strategy slot it holds in `auto_routers` / `complexity_routers` /+ `adaptive_routers` / `quality_routers`.++ Before this fix, editing an auto-router-family model (a UI save, which reaches+ every other pod as an `upsert_deployment` from the periodic DB reload) popped+ the deployment out of the model_list and then failed to re-add it: registration+ raised "already exists" against the stale registry entry, and+ `ignore_invalid_deployments=True` swallowed the error. The router vanished from+ the Models page and stayed gone until a proxy restart, while the DB row and the+ "saved successfully" response both looked fine.+ """++ @staticmethod+ def _complexity_router_params(default_model: str, tags=None) -> dict:+ return {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {+ "tiers": {"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o", "COMPLEX": "gpt-4o"}+ },+ "complexity_router_default_model": default_model,+ **({"tags": tags} if tags else {}),+ }++ @classmethod+ def _router_with_complexity_router(cls, default_model: str = "gpt-4o") -> "litellm.Router":+ return litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "gpt-4o-mini"}},+ {+ "model_name": "smart-router",+ "litellm_params": cls._complexity_router_params(default_model),+ "model_info": {"id": "router-1", "db_model": True},+ },+ ],+ ignore_invalid_deployments=True,+ )++ @staticmethod+ def _model_names(router: "litellm.Router") -> list:+ return [model["model_name"] for model in router.model_list]++ def test_upsert_of_edited_router_keeps_it_routable(self):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = self._router_with_complexity_router()++ router.upsert_deployment(+ deployment=Deployment(+ model_name="smart-router",+ litellm_params=LiteLLM_Params(**self._complexity_router_params("gpt-4o-mini")),+ model_info=ModelInfo(id="router-1", db_model=True),+ )+ )++ assert "smart-router" in self._model_names(router)+ registered = router.complexity_routers["smart-router"]+ assert len(registered) == 1+ # the surviving strategy is the edited one, not the pre-edit leftover+ assert registered[0].strategy.config.default_model == "gpt-4o-mini"++ def test_unchanged_upsert_leaves_router_untouched(self):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = self._router_with_complexity_router()+ strategy_before = router.complexity_routers["smart-router"][0].strategy++ for _ in range(3):+ router.upsert_deployment(+ deployment=Deployment(+ model_name="smart-router",+ litellm_params=LiteLLM_Params(**self._complexity_router_params("gpt-4o")),+ model_info=ModelInfo(id="router-1", db_model=True),+ )+ )++ assert "smart-router" in self._model_names(router)+ assert router.complexity_routers["smart-router"][0].strategy is strategy_before++ def test_delete_frees_the_name_for_a_new_router(self):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = self._router_with_complexity_router()++ router.delete_deployment(id="router-1")+ assert "smart-router" not in router.complexity_routers++ router.add_deployment(+ deployment=Deployment(+ model_name="smart-router",+ litellm_params=LiteLLM_Params(**self._complexity_router_params("gpt-4o-mini")),+ model_info=ModelInfo(id="router-2", db_model=True),+ )+ )++ assert "smart-router" in self._model_names(router)+ assert router.complexity_routers["smart-router"][0].strategy.config.default_model == "gpt-4o-mini"++ def test_delete_only_frees_the_matching_tag_slot(self):+ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "gpt-4o-mini"}},+ {+ "model_name": "shared-router",+ "litellm_params": self._complexity_router_params("gpt-4o", tags=["team-a"]),+ "model_info": {"id": "router-a"},+ },+ {+ "model_name": "shared-router",+ "litellm_params": self._complexity_router_params("gpt-4o-mini", tags=["team-b"]),+ "model_info": {"id": "router-b"},+ },+ ],+ ignore_invalid_deployments=True,+ )+ assert len(router.complexity_routers["shared-router"]) == 2++ router.delete_deployment(id="router-a")++ remaining = router.complexity_routers["shared-router"]+ assert len(remaining) == 1+ assert remaining[0].tags == ("team-b",)++ def test_delete_of_regular_model_preserves_router_sharing_its_name(self):+ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "gpt-4o-mini"}},+ {+ "model_name": "shared-name",+ "litellm_params": self._complexity_router_params("gpt-4o"),+ "model_info": {"id": "router-1"},+ },+ {+ "model_name": "shared-name",+ "litellm_params": {"model": "openai/gpt-4o"},+ "model_info": {"id": "regular-1"},+ },+ ],+ ignore_invalid_deployments=True,+ )+ strategy = router.complexity_routers["shared-name"][0].strategy++ router.delete_deployment(id="regular-1")++ assert router.complexity_routers["shared-name"][0].strategy is strategy++ def test_upsert_of_edited_adaptive_router_rebuilds_it(self):+ """Adaptive routers are built by set_model_list()'s deferred pass, not by+ add_deployment(), so releasing the slot on edit must be paired with a rebuild -+ otherwise the edit silently turns adaptive routing off."""+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ def adaptive_params(available_models: list) -> dict:+ return {+ "model": "auto_router/adaptive_router",+ "adaptive_router_config": {"available_models": available_models},+ }++ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},+ {+ "model_name": "adaptive-router",+ "litellm_params": adaptive_params(["gpt-4o-mini"]),+ "model_info": {"id": "router-1", "db_model": True},+ },+ ],+ ignore_invalid_deployments=True,+ )+ assert "adaptive-router" in router.adaptive_routers++ router.upsert_deployment(+ deployment=Deployment(+ model_name="adaptive-router",+ litellm_params=LiteLLM_Params(**adaptive_params(["gpt-4o", "gpt-4o-mini"])),+ model_info=ModelInfo(id="router-1", db_model=True),+ )+ )++ assert "adaptive-router" in self._model_names(router)+ registered = router.adaptive_routers["adaptive-router"]+ assert len(registered) == 1+ assert set(registered[0].strategy.config.available_models) == {"gpt-4o", "gpt-4o-mini"}++ def test_delete_repairs_indices_even_when_strategy_release_fails(self):+ """Structural removal and strategy release are not equally critical. Once the entry+ leaves model_list the index maps must be repaired no matter what, so releasing the+ registry slot runs after that repair and cannot abandon the router half-updated."""+ router = self._router_with_complexity_router()+ idx = router.model_id_to_deployment_index_map["router-1"]+ router.model_list[idx] = {"model_name": "smart-router", "litellm_params": None}++ returned = router.delete_deployment(id="router-1")++ assert returned is not None+ assert "router-1" not in router.model_id_to_deployment_index_map+ assert all(entry.get("model_info", {}).get("id") != "router-1" for entry in router.model_list)+ assert router.get_deployment(model_id="router-1") is None+ assert "gpt-4o" in self._model_names(router)++ def test_delete_of_adaptive_enabled_complexity_router_frees_both_registries(self):+ """A complexity router with adaptive set is registered in BOTH complexity_routers+ and adaptive_routers under the same (model_name, tags). Releasing only the first+ match leaves the adaptive strategy live, so a deleted alias stays routable and its+ post-call hook keeps recording."""+ import litellm as litellm_module+ from litellm.router_strategy.adaptive_router.hooks import AdaptiveRouterPostCallHook++ params = {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {+ "tiers": {"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o"},+ "adaptive": True,+ },+ "complexity_router_default_model": "gpt-4o",+ }+ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},+ {+ "model_name": "hybrid-router",+ "litellm_params": params,+ "model_info": {"id": "router-1", "db_model": True},+ },+ ],+ ignore_invalid_deployments=True,+ )+ assert "hybrid-router" in router.complexity_routers+ assert "hybrid-router" in router.adaptive_routers+ hooks = litellm_module.logging_callback_manager.get_custom_loggers_for_type(AdaptiveRouterPostCallHook)+ assert len(hooks) == 1++ router.delete_deployment(id="router-1")++ assert "hybrid-router" not in router.complexity_routers+ assert "hybrid-router" not in router.adaptive_routers+ remaining_hooks = litellm_module.logging_callback_manager.get_custom_loggers_for_type(+ AdaptiveRouterPostCallHook+ )+ assert remaining_hooks == []++ def test_upsert_of_edited_quality_router_keeps_it_routable(self):+ """_unregister_pre_routing_strategy_for_deployment dispatches on four prefixes;+ quality_router is one of them and would otherwise go unexercised."""+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ def quality_params(default_model: str) -> dict:+ return {+ "model": "auto_router/quality_router",+ "quality_router_default_model": default_model,+ }++ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},+ {+ "model_name": "quality-router",+ "litellm_params": quality_params("gpt-4o"),+ "model_info": {"id": "router-1", "db_model": True},+ },+ ],+ ignore_invalid_deployments=True,+ )+ assert "quality-router" in router.quality_routers++ router.upsert_deployment(+ deployment=Deployment(+ model_name="quality-router",+ litellm_params=LiteLLM_Params(**quality_params("gpt-4o-mini")),+ model_info=ModelInfo(id="router-1", db_model=True),+ )+ )++ assert "quality-router" in self._model_names(router)+ registered = router.quality_routers["quality-router"]+ assert len(registered) == 1+ assert registered[0].strategy.config.default_model == "gpt-4o-mini"++ @staticmethod+ def _hybrid_router_params(tiers: dict) -> dict:+ return {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {"tiers": tiers, "adaptive": True},+ "complexity_router_default_model": "gpt-4o",+ }++ @classmethod+ def _router_with_hybrid_router(cls) -> "litellm.Router":+ return litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},+ {+ "model_name": "hybrid-router",+ "litellm_params": cls._hybrid_router_params({"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o"}),+ "model_info": {"id": "router-1", "db_model": True},+ },+ ],+ ignore_invalid_deployments=True,+ )++ def test_upsert_of_edited_hybrid_complexity_router_relinks_adaptive(self):+ """Editing an adaptive-enabled complexity router releases its adaptive companion+ along with the complexity slot; the finalize re-run must fire for it (not just for+ `auto_router/adaptive_router` deployments) or the rebuilt complexity router keeps+ routing while bandit recording, DB persistence and /adaptive_router/state all+ silently stop until the next full reload."""+ import litellm as litellm_module+ from litellm.router_strategy.adaptive_router.hooks import AdaptiveRouterPostCallHook+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = self._router_with_hybrid_router()+ assert "hybrid-router" in router.adaptive_routers++ router.upsert_deployment(+ deployment=Deployment(+ model_name="hybrid-router",+ litellm_params=LiteLLM_Params(+ **self._hybrid_router_params(+ {"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o", "COMPLEX": "gpt-4o"}+ )+ ),+ model_info=ModelInfo(id="router-1", db_model=True),+ )+ )++ assert "hybrid-router" in self._model_names(router)+ assert "hybrid-router" in router.complexity_routers+ assert "hybrid-router" in router.adaptive_routers+ rebuilt = router.complexity_routers["hybrid-router"][0].strategy+ assert router.adaptive_routers["hybrid-router"][0].strategy is rebuilt.adaptive_router+ hooks = litellm_module.logging_callback_manager.get_custom_loggers_for_type(AdaptiveRouterPostCallHook)+ assert len(hooks) == 1++ def test_upsert_turning_adaptive_on_builds_the_companion(self):+ """An edit that flips `adaptive: true` on an existing complexity router must+ register the companion immediately; neither side of the old prefix-only gate+ matches a complexity deployment, so the flip was a silent no-op until restart."""+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = self._router_with_complexity_router()+ assert "smart-router" not in router.adaptive_routers++ params = self._complexity_router_params("gpt-4o")+ params["complexity_router_config"] = {**params["complexity_router_config"], "adaptive": True}+ router.upsert_deployment(+ deployment=Deployment(+ model_name="smart-router",+ litellm_params=LiteLLM_Params(**params),+ model_info=ModelInfo(id="router-1", db_model=True),+ )+ )++ assert "smart-router" in router.adaptive_routers++ def test_unregister_pre_routing_strategy_scopes_the_drop_by_tags(self):+ """The bool return drives the hook re-sync; a tag mismatch must report False and+ leave the registry untouched, and dropping the last entry must free the key."""+ from litellm.types.router import TaggedPreRoutingStrategy++ registry = {+ "m": [+ TaggedPreRoutingStrategy(tags=("team-a",), strategy=object()),+ TaggedPreRoutingStrategy(tags=(), strategy=object()),+ ]+ }++ assert litellm.Router._unregister_pre_routing_strategy(registry, "m", ("team-b",)) is False+ assert len(registry["m"]) == 2++ assert litellm.Router._unregister_pre_routing_strategy(registry, "m", ("team-a",)) is True+ assert [entry.tags for entry in registry["m"]] == [()]++ assert litellm.Router._unregister_pre_routing_strategy(registry, "m", ()) is True+ assert "m" not in registry++ def test_unregister_for_deployment_ignores_non_router_deployments(self):+ """Direct twin of the endpoint-level test: a regular deployment that shares a+ router's model_name must not evict the router's registry slot."""+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = self._router_with_complexity_router()++ router._unregister_pre_routing_strategy_for_deployment(+ deployment=Deployment(+ model_name="smart-router",+ litellm_params=LiteLLM_Params(model="openai/gpt-4o"),+ model_info=ModelInfo(id="plain-1", db_model=True),+ )+ )++ assert "smart-router" in router.complexity_routers++ def test_sync_adaptive_router_hooks_keeps_one_hook_per_registered_router(self):+ """Re-syncing must replace, not accumulate: a duplicated hook double-fires+ bandit signal recording for every request."""+ import litellm as litellm_module+ from litellm.router_strategy.adaptive_router.hooks import AdaptiveRouterPostCallHook++ router = self._router_with_hybrid_router()++ router._sync_adaptive_router_hooks()+ router._sync_adaptive_router_hooks()++ hooks = litellm_module.logging_callback_manager.get_custom_loggers_for_type(AdaptiveRouterPostCallHook)+ assert len(hooks) == 1++ def test_deployment_participates_in_adaptive_routing_matrix(self):+ """The upsert finalize re-run keys off this predicate for both the incoming and+ outgoing deployment; a false negative silently strands the adaptive companion."""+ from litellm.types.router import LiteLLM_Params++ router = self._router_with_complexity_router()++ cases = [+ ({"model": "auto_router/adaptive_router", "adaptive_router_config": {}}, True),+ (self._hybrid_router_params({"SIMPLE": "gpt-4o-mini"}), True),+ (self._complexity_router_params("gpt-4o"), False),+ (+ {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {"tiers": {"SIMPLE": "gpt-4o-mini"}, "adaptive": False},+ "complexity_router_default_model": "gpt-4o",+ },+ False,+ ),+ ({"model": "openai/gpt-4o"}, False),+ ]+ for params, expected in cases:+ actual = router._deployment_participates_in_adaptive_routing(+ litellm_params=LiteLLM_Params(**params)+ )+ assert actual is expected, params["model"]+++ def test_model_info_is_active_for_environment_matrix(monkeypatch):+ """The model-write endpoints consult this predicate to tell a deliberately+ environment-inactive model from one dropped by a failed reload; the Router's own+ deployment gate delegates to it, so the two can never diverge."""+ from litellm.router import model_info_is_active_for_environment++ assert model_info_is_active_for_environment(model_info=None) is True+ assert model_info_is_active_for_environment(model_info={"id": "m1"}) is True+ assert model_info_is_active_for_environment(model_info={"supported_environments": None}) is True++ monkeypatch.setenv("LITELLM_ENVIRONMENT", "development")+ assert model_info_is_active_for_environment(model_info={"supported_environments": ["development"]}) is True+ assert model_info_is_active_for_environment(model_info={"supported_environments": ["production"]}) is False++ monkeypatch.delenv("LITELLM_ENVIRONMENT")+ with pytest.raises(ValueError, match="LITELLM_ENVIRONMENT"):+ model_info_is_active_for_environment(model_info={"supported_environments": ["production"]})+++ def test_pre_call_checks_uses_deployment_model_when_model_info_lookup_raises(monkeypatch):+ """+ The supported-params check must run against the deployment's own+ provider-qualified model. Resolving the per-deployment model only after the+ model-info lookup leaves it unset whenever that lookup raises (an+ unregistered custom model), so the check falls back to the bare model group+ name and the request dies with 'LLM Provider NOT provided'.+ """+ monkeypatch.setattr(litellm, "drop_params", False)++ router = litellm.Router(+ model_list=[+ {+ "model_name": "custom-alias",+ "litellm_params": {"model": "hosted_vllm/not-in-the-catalog"},+ }+ ],+ enable_pre_call_checks=True,+ )++ def _raise_unmapped(**kwargs):+ raise ValueError("This model isn't mapped yet")++ monkeypatch.setattr(router, "get_router_model_info", _raise_unmapped)++ seen: list[tuple] = []+ original_get_supported_openai_params = litellm.get_supported_openai_params++ def _record(model, custom_llm_provider=None, **kwargs):+ seen.append((model, custom_llm_provider))+ return original_get_supported_openai_params(model=model, custom_llm_provider=custom_llm_provider, **kwargs)++ monkeypatch.setattr(litellm, "get_supported_openai_params", _record)++ deployments = [+ {+ "litellm_params": {"model": "hosted_vllm/not-in-the-catalog"},+ "model_info": {"id": "d1"},+ }+ ]+ result = router._pre_call_checks(+ model="custom-alias",+ healthy_deployments=deployments,+ messages=[{"role": "user", "content": "hi"}],+ request_kwargs={},+ )++ assert len(result) == 1+ assert seen == [("not-in-the-catalog", "hosted_vllm")]+++ def test_pre_call_checks_keeps_deployment_when_provider_is_unresolvable(monkeypatch):+ """+ Pre-call checks filter deployments; they must never be the thing that fails+ a request. A deployment whose provider cannot be resolved simply skips the+ supported-params check instead of raising out of deployment selection.+ """+ monkeypatch.setattr(litellm, "drop_params", False)++ router = litellm.Router(+ model_list=[+ {+ "model_name": "custom-alias",+ "litellm_params": {"model": "gpt-3.5-turbo"},+ }+ ],+ enable_pre_call_checks=True,+ )++ def _raise_no_provider(**kwargs):+ raise litellm.BadRequestError(+ message="LLM Provider NOT provided.",+ model="custom-alias",+ llm_provider="",+ )++ monkeypatch.setattr(litellm, "get_llm_provider", _raise_no_provider)++ deployments = [+ {+ "litellm_params": {"model": "some-unresolvable-model"},+ "model_info": {"id": "d1"},+ }+ ]+ result = router._pre_call_checks(+ model="custom-alias",+ healthy_deployments=deployments,+ messages=[{"role": "user", "content": "hi"}],+ request_kwargs={},+ )++ assert len(result) == 1+++ class TestUpsertDeploymentRollback:+ """+ Regression tests: `upsert_deployment` pops the previous deployment before+ re-adding the edited one. When the re-add raises under+ `ignore_invalid_deployments=True`, the pop must be rolled back so this pod+ keeps serving the previous configuration instead of silently dropping a live+ deployment (the "Error upserting deployment" drop behind the access-group+ reload 500 in the 2-replica e2e suite).+ """++ def test_failed_upsert_keeps_previous_deployment_serving(self):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = litellm.Router(+ model_list=[+ {+ "model_name": "prod-model",+ "litellm_params": {"model": "gpt-4o", "api_key": "sk-old"},+ "model_info": {"id": "prod-1", "db_model": True},+ }+ ],+ ignore_invalid_deployments=True,+ )++ result = router.upsert_deployment(+ deployment=Deployment(+ model_name="prod-model",+ litellm_params=LiteLLM_Params(model="auto_router/broken"),+ model_info=ModelInfo(id="prod-1", db_model=True),+ )+ )++ assert result is None+ restored = router.get_deployment(model_id="prod-1")+ assert restored is not None+ assert restored.litellm_params.model == "gpt-4o"+ assert [model["model_name"] for model in router.model_list] == ["prod-model"]++ def test_failed_fresh_add_returns_none_without_restore(self):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = litellm.Router(model_list=[], ignore_invalid_deployments=True)++ result = router.upsert_deployment(+ deployment=Deployment(+ model_name="fresh-router",+ litellm_params=LiteLLM_Params(model="auto_router/broken"),+ model_info=ModelInfo(id="fresh-1", db_model=True),+ )+ )++ assert result is None+ assert router.get_deployment(model_id="fresh-1") is None+ assert router.model_list == []++ def test_restore_re_adds_popped_deployment(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "prod-model",+ "litellm_params": {"model": "gpt-4o", "api_key": "sk-old"},+ "model_info": {"id": "prod-1", "db_model": True},+ }+ ],+ ignore_invalid_deployments=True,+ )+ previous = router.get_deployment(model_id="prod-1")+ router.delete_deployment(id="prod-1")+ assert router.has_model_id("prod-1") is False++ router._restore_deployment_after_failed_upsert(+ previous_deployment=previous, model_id="prod-1"+ )++ restored = router.get_deployment(model_id="prod-1")+ assert restored is not None+ assert restored.litellm_params.model == "gpt-4o"++ router._restore_deployment_after_failed_upsert(+ previous_deployment=previous, model_id="prod-1"+ )+ assert len(router.model_list) == 1++ router._restore_deployment_after_failed_upsert(+ previous_deployment=None, model_id="prod-1"+ )+ assert len(router.model_list) == 1+++ class TestUpsertDeploymentRename:+ """+ Issue #38360: renaming a model wrote the new `model_name` to the db, but the reload's+ `upsert_deployment` compared only `litellm_params` and `model_info`. A rename with no+ other edit therefore compared equal and the router kept the old name until a restart,+ so `/model/info` and `/v1/models` served the stale name and the new one was unroutable.+ """++ @staticmethod+ def _router() -> "litellm.Router":+ return litellm.Router(+ model_list=[+ {+ "model_name": "old-name",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-test"},+ "model_info": {"id": "rename-1", "db_model": True},+ }+ ]+ )++ @staticmethod+ def _deployment(model_name: str, tpm: int | None = None):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ return Deployment(+ model_name=model_name,+ litellm_params=LiteLLM_Params(model="openai/gpt-4o", api_key="sk-test", tpm=tpm),+ model_info=ModelInfo(id="rename-1", db_model=True),+ )++ def test_rename_only_updates_the_router(self):+ router = self._router()++ assert router.upsert_deployment(deployment=self._deployment("new-name")) is not None++ assert [model["model_name"] for model in router.model_list] == ["new-name"]+ renamed = router.get_deployment(model_id="rename-1")+ assert renamed is not None+ assert renamed.model_name == "new-name"++ def test_rename_only_makes_the_new_name_routable(self):+ router = self._router()++ router.upsert_deployment(deployment=self._deployment("new-name"))++ assert router.get_model_ids(model_name="new-name") == ["rename-1"]+ assert router.get_model_ids(model_name="old-name") == []++ def test_rename_alongside_another_edit_still_updates(self):+ router = self._router()++ router.upsert_deployment(deployment=self._deployment("new-name", tpm=1234))++ assert router.get_model_ids(model_name="new-name") == ["rename-1"]+ renamed = router.get_deployment(model_id="rename-1")+ assert renamed is not None+ assert renamed.litellm_params.tpm == 1234++ def test_unchanged_deployment_is_still_a_no_op(self):+ router = self._router()++ assert router.upsert_deployment(deployment=self._deployment("old-name")) is None+ assert [model["model_name"] for model in router.model_list] == ["old-name"]+++ class TestConsumedRequestTagsStamp:+ """Issue #36621: when a request's tags select a tagged pre-routing strategy, those+ tags are consumed by the selection; the hook must stamp the rewritten model group so+ tag filtering skips request-body tags there, and must clear the stamp on every+ re-entry (fallbacks reuse the same request_kwargs) so it cannot leak elsewhere."""++ class _RewriteStrategy:+ def __init__(self, rewrite_to: str):+ self.rewrite_to = rewrite_to++ async def async_pre_routing_hook(+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False+ ):+ from litellm.types.router import PreRoutingHookResponse++ return PreRoutingHookResponse(model=self.rewrite_to, messages=messages)++ @classmethod+ def _router(cls, marker_tags=("route",)) -> "litellm.Router":+ from litellm.types.router import TaggedPreRoutingStrategy++ router = litellm.Router(+ model_list=[+ {"model_name": "gpt4o", "litellm_params": {"model": "openai/gpt-4o"}},+ {"model_name": "gemini-flash", "litellm_params": {"model": "gemini/gemini-3.6-flash"}},+ ],+ enable_tag_filtering=True,+ )+ router.auto_routers = {+ "gpt4o": [TaggedPreRoutingStrategy(tags=marker_tags, strategy=cls._RewriteStrategy("gemini-flash"))]+ }+ return router++ @pytest.mark.asyncio+ async def test_stamps_the_rewritten_group_when_request_tags_selected_the_router(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY+ from litellm.types.router import ConsumedRequestTagsStamp++ router = self._router()+ request_kwargs = {"metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert request_kwargs["metadata"][CONSUMED_REQUEST_TAGS_METADATA_KEY] == ConsumedRequestTagsStamp(+ model_group="gemini-flash", tags=("route",)+ )++ @pytest.mark.asyncio+ async def test_stamps_into_litellm_metadata_when_the_request_uses_that_bucket(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY+ from litellm.types.router import ConsumedRequestTagsStamp++ router = self._router()+ request_kwargs = {"litellm_metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert request_kwargs["litellm_metadata"][CONSUMED_REQUEST_TAGS_METADATA_KEY] == ConsumedRequestTagsStamp(+ model_group="gemini-flash", tags=("route",)+ )++ @pytest.mark.asyncio+ async def test_fallback_reentry_with_a_plain_group_clears_the_stale_stamp(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY++ router = self._router()+ request_kwargs = {"metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)+ await router.async_pre_routing_hook(model="gemini-flash", request_kwargs=request_kwargs)++ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]++ @pytest.mark.asyncio+ async def test_no_stamp_when_the_request_is_untagged(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY++ router = self._router()+ request_kwargs = {"metadata": {}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]++ @pytest.mark.asyncio+ async def test_no_stamp_when_the_selected_strategy_carries_no_tags(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY++ router = self._router(marker_tags=())+ request_kwargs = {"metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]+++ class TestAutoRouterMaxInputCharsWiring:+ """`auto_router_max_input_chars` on the deployment has to reach the AutoRouter that embeds prompts.++ Without it the cap silently reverts to the default, so an operator whose embedding model has a+ 512-token window cannot lower it and every long prompt falls back to the default model instead+ of being routed.+ """++ @staticmethod+ def _router(**extra_params) -> "litellm.Router":+ pytest.importorskip("semantic_router", reason="auto-router needs the semantic-router extra")+ return litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},+ {+ "model_name": "my-auto-router",+ "litellm_params": {+ "model": "auto_router/my-auto-router",+ "auto_router_config": json.dumps(+ {"routes": [{"name": "gpt-4o", "utterances": ["write me code"]}]}+ ),+ "auto_router_default_model": "gpt-4o",+ "auto_router_embedding_model": "text-embedding-3-small",+ **extra_params,+ },+ },+ ]+ )++ @staticmethod+ def _registered_auto_router(router: "litellm.Router"):+ return router.auto_routers["my-auto-router"][0].strategy++ def test_should_pass_the_configured_cap_to_the_auto_router(self):+ router = self._router(auto_router_max_input_chars=512)++ assert self._registered_auto_router(router).max_input_chars == 512++ def test_should_fall_back_to_the_shared_default_when_the_deployment_omits_it(self):+ from litellm.constants import DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS++ router = self._router()++ assert self._registered_auto_router(router).max_input_chars == DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS+++ class TestTaggedAutoRouterOnSharedModelName:+ """A tagged auto-router marker sharing its model_name with a plain deployment must not+ capture requests whose tags don't match it when tag filtering is enabled (#36620)."""++ class _FixedRouteLayer:+ def __call__(self, text: str):+ from semantic_router.schema import RouteChoice++ return RouteChoice(name="gemini-flash")++ @classmethod+ def _router(cls, marker_tags, include_plain_sibling: bool, enable_tag_filtering: bool) -> "litellm.Router":+ pytest.importorskip("semantic_router", reason="auto-router needs the semantic-router extra")+ marker = {+ "model_name": "gpt4o",+ "litellm_params": {+ "model": "auto_router/gpt4o-router",+ "auto_router_config": json.dumps(+ {"routes": [{"name": "gemini-flash", "utterances": ["capital city questions"]}]}+ ),+ "auto_router_default_model": "gemini-flash",+ "auto_router_embedding_model": "text-embedding-3-small",+ **({"tags": marker_tags} if marker_tags else {}),+ },+ }+ plain = {"model_name": "gpt4o", "litellm_params": {"model": "openai/gpt-4o"}}+ tier = {"model_name": "gemini-flash", "litellm_params": {"model": "gemini/gemini-3.6-flash"}}+ router = litellm.Router(+ model_list=[plain, marker, tier] if include_plain_sibling else [marker, tier],+ enable_tag_filtering=enable_tag_filtering,+ )+ router.auto_routers["gpt4o"][0].strategy.routelayer = cls._FixedRouteLayer()+ return router++ @staticmethod+ async def _hook_response(router: "litellm.Router", request_kwargs: dict):+ return await router.async_pre_routing_hook(+ model="gpt4o",+ request_kwargs=request_kwargs,+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ )++ @pytest.mark.asyncio+ async def test_untagged_request_bypasses_the_tagged_marker_when_a_plain_deployment_shares_the_name(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)++ assert await self._hook_response(router, {}) is None++ @pytest.mark.asyncio+ async def test_request_tagged_for_the_marker_is_still_semantically_routed(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)++ response = await self._hook_response(router, {"metadata": {"tags": ["route"]}})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_request_level_tag_filtering_from_key_settings_bypasses_the_marker(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=False)++ assert await self._hook_response(router, {"enable_tag_filtering": True}) is None++ @pytest.mark.asyncio+ async def test_globally_disabled_filtering_still_lets_the_marker_capture_untagged_requests(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=False)++ response = await self._hook_response(router, {})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_marker_only_alias_still_captures_untagged_requests(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=False, enable_tag_filtering=True)++ response = await self._hook_response(router, {})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_untagged_marker_sharing_the_name_still_captures_untagged_requests(self):+ router = self._router(marker_tags=None, include_plain_sibling=True, enable_tag_filtering=True)++ response = await self._hook_response(router, {})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_untagged_selection_never_lands_on_the_marker_deployment(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)++ for _ in range(20):+ deployment = await router.async_get_available_deployment(+ model="gpt4o",+ request_kwargs={},+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ )+ assert deployment["litellm_params"]["model"] == "openai/gpt-4o"++ def test_deployment_without_litellm_params_mapping_is_not_a_marker(self):+ assert litellm.Router._is_strategy_marker_deployment({"model_name": "gpt4o"}) is False++ def test_model_name_has_plain_deployments_reflects_the_pool(self):+ mixed = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)+ marker_only = self._router(marker_tags=["route"], include_plain_sibling=False, enable_tag_filtering=True)++ assert mixed._model_name_has_plain_deployments("gpt4o") is True+ assert marker_only._model_name_has_plain_deployments("gpt4o") is False+++ class TestAutoRouterSharedModelNameConnectionParams:+ """A plain deployment sharing its model_name with an `auto_router/` marker must not have+ its api_base and api_key grafted onto the routed tier's outbound call (#36619)."""++ PLAIN_API_BASE = "https://plain-sibling.openai.example/v1"+ PLAIN_API_KEY = "sk-plain-sibling-secret"++ class _FixedRouteLayer:+ def __call__(self, text: str):+ from semantic_router.schema import RouteChoice++ return RouteChoice(name="gemini-flash")++ @classmethod+ def _router(cls, plain_entry_first: bool) -> "litellm.Router":+ pytest.importorskip("semantic_router", reason="auto-router needs the semantic-router extra")+ plain = {+ "model_name": "gpt4o",+ "litellm_params": {+ "model": "openai/gpt-4o",+ "api_key": cls.PLAIN_API_KEY,+ "api_base": cls.PLAIN_API_BASE,+ },+ }+ marker = {+ "model_name": "gpt4o",+ "litellm_params": {+ "model": "auto_router/gpt4o-router",+ "auto_router_config": json.dumps(+ {"routes": [{"name": "gemini-flash", "utterances": ["capital city questions"]}]}+ ),+ "auto_router_default_model": "gemini-flash",+ "auto_router_embedding_model": "text-embedding-3-small",+ "drop_params": True,+ },+ }+ tier = {+ "model_name": "gemini-flash",+ "litellm_params": {"model": "gemini/gemini-3.6-flash", "api_key": "sk-tier-key"},+ }+ shared_name_entries = [plain, marker] if plain_entry_first else [marker, plain]+ router = litellm.Router(model_list=[*shared_name_entries, tier])+ router.auto_routers["gpt4o"][0].strategy.routelayer = cls._FixedRouteLayer()+ return router++ @staticmethod+ def _gemini_response() -> httpx.Response:+ return httpx.Response(+ status_code=200,+ json={+ "candidates": [+ {"content": {"parts": [{"text": "Paris"}], "role": "model"}, "finishReason": "STOP"}+ ],+ "usageMetadata": {"promptTokenCount": 5, "candidatesTokenCount": 1, "totalTokenCount": 6},+ "modelVersion": "gemini-3.6-flash",+ },+ request=httpx.Request("POST", "https://generativelanguage.googleapis.com"),+ )++ @pytest.mark.parametrize(+ "plain_entry_first", [True, False], ids=["plain_entry_first", "marker_entry_first"]+ )+ async def test_routed_tier_call_goes_out_on_its_own_endpoint_and_credentials(self, plain_entry_first):+ """The outbound provider request for the routed tier hits the tier's own Gemini host+ with the tier's own key, never the plain sibling's api_base or api_key."""+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler++ router = self._router(plain_entry_first)++ with patch.object(+ AsyncHTTPHandler, "post", new_callable=AsyncMock, return_value=self._gemini_response()+ ) as mock_post:+ await router.acompletion(+ model="gpt4o",+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ )++ call = mock_post.call_args+ outbound_url = str(call.kwargs["url"] if "url" in call.kwargs else call.args[0])+ outbound_headers = dict(call.kwargs.get("headers") or {})++ assert "generativelanguage.googleapis.com" in outbound_url+ assert "gemini-3.6-flash" in outbound_url+ assert self.PLAIN_API_BASE not in outbound_url+ assert self.PLAIN_API_KEY not in outbound_url+ assert self.PLAIN_API_KEY not in json.dumps(outbound_headers)+++ class TestGetAllowedFailsFromPolicy:+ def _make_router(self, **policy_kwargs) -> litellm.Router:+ from litellm.types.router import AllowedFailsPolicy++ return litellm.Router(+ model_list=[{"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "fake"}}],+ allowed_fails_policy=AllowedFailsPolicy(**policy_kwargs),+ )++ def test_no_policy_returns_none(self):+ router = litellm.Router(+ model_list=[{"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "fake"}}],+ )+ assert router.get_allowed_fails_from_policy(litellm.RateLimitError("429", "openai", "gpt-4")) is None++ def test_internal_server_error_allowed_fails(self):+ router = self._make_router(InternalServerErrorAllowedFails=7)+ exc = litellm.InternalServerError("500", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 7++ def test_service_unavailable_error_allowed_fails(self):+ router = self._make_router(ServiceUnavailableErrorAllowedFails=4)+ exc = litellm.ServiceUnavailableError("503", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 4++ def test_bad_gateway_error_allowed_fails(self):+ router = self._make_router(BadGatewayErrorAllowedFails=2)+ exc = litellm.BadGatewayError("502", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 2++ def test_not_found_error_allowed_fails(self):+ router = self._make_router(NotFoundErrorAllowedFails=1)+ exc = litellm.NotFoundError("404", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 1++ def test_unmatched_exception_returns_none(self):+ router = self._make_router(InternalServerErrorAllowedFails=5)+ exc = litellm.RateLimitError("429", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) is None+++ class _LogCapture(logging.Handler):+ def __init__(self, level):+ super().__init__(level=level)+ self._level = level+ self.messages = []++ def emit(self, record):+ if record.levelno == self._level:+ self.messages.append(record.getMessage())+++ class _FallbackAttemptRecorder(CustomLogger):+ def __init__(self):+ super().__init__()+ self.failed_targets = []++ async def log_failure_fallback_event(self, original_model_group, kwargs, original_exception):+ self.failed_targets.append(kwargs.get("model"))+++ def _cyclic_fallback_router(num_retries=0):+ groups = ["group-a", "group-b", "group-c", "group-d"]+ return litellm.Router(+ model_list=[+ {+ "model_name": group,+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-fake",+ "mock_response": "litellm.InternalServerError",+ },+ }+ for group in groups+ ],+ fallbacks=[+ {"group-a": ["group-b", "group-c"]},+ {"group-b": ["group-a", "group-c"]},+ {"group-c": ["group-d"]},+ {"group-d": ["group-b", "group-a"]},+ ],+ num_retries=num_retries,+ )+++ async def _drive_cyclic_fallback(router, capture, recorder=None, **request_kwargs):+ router_logger = logging.getLogger("LiteLLM Router")+ previous_level = router_logger.level+ router_logger.setLevel(capture.level)+ router_logger.addHandler(capture)+ if recorder is not None:+ litellm.callbacks.append(recorder)+ try:+ with pytest.raises(litellm.InternalServerError):+ await router.acompletion(+ model="group-a", messages=[{"role": "user", "content": "hi"}], **request_kwargs+ )+ finally:+ router_logger.removeHandler(capture)+ router_logger.setLevel(previous_level)+ if recorder is not None:+ litellm.callbacks.remove(recorder)+++ @pytest.mark.asyncio+ async def test_cyclic_fallback_graph_does_not_amplify_one_request():+ """A fallback graph whose entries loop back on each other is easy to build by accident,+ and every group in the loop fails identically on a deterministic error, so the walk must+ not revisit a group and must not re-emit a growing chained traceback at each level. Left+ unbounded, one request blocks the event loop long enough for health probes to fail."""+ recorder = _FallbackAttemptRecorder()+ capture = _LogCapture(logging.ERROR)++ await _drive_cyclic_fallback(_cyclic_fallback_router(), capture, recorder)++ assert sorted(set(recorder.failed_targets)) == ["group-b", "group-c", "group-d"]+ assert len(recorder.failed_targets) == len(set(recorder.failed_targets))+ assert not any("Traceback (most recent call last)" in message for message in capture.messages)+ assert sum(len(message) for message in capture.messages) < 5_000+++ @pytest.mark.asyncio+ async def test_retry_breadcrumbs_do_not_carry_the_walk_state():+ """log_retry copies every kwarg into previous_models, which reaches spend logs and+ logging callbacks. The set of already-attempted groups is router-internal walk state+ with no diagnostic value there, and it is the one entry that is not a plain scalar.+ A retry has to be configured for the walk state to reach log_retry at all."""+ router = _cyclic_fallback_router(num_retries=1)+ capture = _LogCapture(logging.ERROR)++ await _drive_cyclic_fallback(router, capture)++ assert router.previous_models, "no retry breadcrumbs were recorded"+ assert any(+ "fallback_depth" in breadcrumb for breadcrumb in router.previous_models+ ), "no breadcrumb carried router walk state, so this test cannot see the leak"+ for breadcrumb in router.previous_models:+ assert "attempted_targets" not in breadcrumb+++ _BREADCRUMB_CREDENTIAL_CANARY = "Bearer sk-ant-oat01-RETRY-BREADCRUMB-CANARY-doNotShip"+++ @pytest.mark.parametrize(+ "container_key, request_kwargs",+ [+ (+ "provider_specific_header",+ {+ "provider_specific_header": {+ "custom_llm_provider": "openai",+ "extra_headers": {"authorization": _BREADCRUMB_CREDENTIAL_CANARY},+ }+ },+ ),+ (+ "extra_headers",+ {"extra_headers": {"authorization": _BREADCRUMB_CREDENTIAL_CANARY}},+ ),+ (+ "api_key",+ {"api_key": _BREADCRUMB_CREDENTIAL_CANARY},+ ),+ ],+ )+ @pytest.mark.asyncio+ async def test_retry_breadcrumbs_never_carry_a_forwarded_credential(container_key, request_kwargs):+ """log_retry copies kwargs into previous_models, which reaches spend logs and logging callbacks.+ Any of these kwargs can carry a client's forwarded Authorization token or a provider key, and a+ breadcrumb has no diagnostic use for the raw secret. A denylist of key names is always one new+ credential kwarg behind, so log_retry scrubs credential-named values by pattern instead: the+ container still reaches the breadcrumb, but the raw secret never does, whatever key holds it."""+ router = _cyclic_fallback_router(num_retries=1)+ capture = _LogCapture(logging.ERROR)++ await _drive_cyclic_fallback(router, capture, **request_kwargs)++ assert router.previous_models, "no retry breadcrumbs were recorded"+ dumped = json.dumps(router.previous_models, default=str)+ assert container_key in dumped, "the credential-bearing kwarg never reached the breadcrumb, so this test cannot see the leak"+ assert _BREADCRUMB_CREDENTIAL_CANARY not in dumped+++ @pytest.mark.asyncio+ async def test_fallback_traceback_stays_available_at_debug_level():+ """Dropping the stack from the ERROR line is only safe because the fallback path still+ emits it once per level at DEBUG, which is what an operator needs to diagnose why every+ fallback failed. This pins that remaining debug traceback."""+ capture = _LogCapture(logging.DEBUG)++ await _drive_cyclic_fallback(_cyclic_fallback_router(), capture)++ assert any("Traceback (most recent call last)" in message for message in capture.messages)+++ @pytest.mark.asyncio+ async def test_fallback_failure_detail_from_upstream_is_bounded():+ """The detail each level records about the level below it is attacker-influenced, since+ it carries whatever the upstream error said. It has to be bounded on its own, so a walk+ over several groups cannot compound one large message into the log or into the message+ handed back to the caller."""+ huge_message = "z" * 50_000+ capture = _LogCapture(logging.ERROR)++ await _drive_cyclic_fallback(+ _cyclic_fallback_router(),+ capture,+ mock_response=litellm.InternalServerError(+ message=huge_message, llm_provider="openai", model="group-a"+ ),+ )++ assert capture.messages, "the fallback failure path did not log at ERROR"+ assert huge_message not in "".join(capture.messages)+ assert max(len(message) for message in capture.messages) < 5_000+++ def test_stamp_or_clear_metadata_key_writes_and_clears_both_buckets():+ request_kwargs = {"metadata": {}}+ litellm.Router._stamp_or_clear_metadata_key(request_kwargs=request_kwargs, key="probe", value=7)+ assert request_kwargs["metadata"]["probe"] == 7++ stale_kwargs = {"metadata": {"probe": 7}, "litellm_metadata": {"probe": 7}}+ litellm.Router._stamp_or_clear_metadata_key(request_kwargs=stale_kwargs, key="probe", value=None)+ assert "probe" not in stale_kwargs["metadata"]+ assert "probe" not in stale_kwargs["litellm_metadata"]+++ @pytest.mark.parametrize(+ "complexity_router_config,expect_callback",+ [+ ({"tiers": {"SIMPLE": "gpt-4o"}}, True),+ ({"tiers": {"SIMPLE": "gpt-4o"}, "deployment_affinity": False}, False),+ ({"tiers": {"SIMPLE": "gpt-4o"}, "deployment_affinity": False, "session_affinity": True}, True),+ ],+ )+ def test_complexity_router_registers_affinity_callback_for_deployment_pin(complexity_router_config, expect_callback):+ """The marker the complexity router stamps is inert unless a DeploymentAffinityCheck is+ registered to read it, so deployment_affinity has to pull the callback in, and its default-on+ means a bare config registers one. Opting out must skip the callback entirely rather than+ register a filter that can never fire, including when session_affinity is on, since the two+ pins are independent."""+ from litellm.router_utils.pre_call_checks.deployment_affinity_check import (+ DeploymentAffinityCheck,+ )++ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},+ {+ "model_name": "my-complexity-router",+ "litellm_params": {+ "model": "auto_router/complexity_router",+ "complexity_router_config": complexity_router_config,+ },+ },+ ]+ )+ try:+ registered = any(isinstance(cb, DeploymentAffinityCheck) for cb in router.optional_callbacks or [])+ assert registered is expect_callback+ finally:+ for cb in router.optional_callbacks or []:+ litellm.logging_callback_manager.remove_callback_from_all_lists(cb)+++ def test_ensure_deployment_affinity_callback_is_idempotent():+ from litellm.router_utils.pre_call_checks.deployment_affinity_check import (+ DeploymentAffinityCheck,+ )++ router = litellm.Router(model_list=[])+ try:+ router._ensure_deployment_affinity_callback()+ router._ensure_deployment_affinity_callback()+ affinity_callbacks = [+ cb for cb in router.optional_callbacks or [] if isinstance(cb, DeploymentAffinityCheck)+ ]+ assert len(affinity_callbacks) == 1+ finally:+ for cb in router.optional_callbacks or []:+ litellm.logging_callback_manager.remove_callback_from_all_lists(cb)+++ def test_get_router_model_info_does_not_wipe_cached_pricing():+ """A Deployment's model_info declares the mirrored pricing fields with None defaults;+ merging it must not write those Nones into the lru_cache'd dict get_model_info() owns,+ or /model/info loses built-in prices for every model a worker serves."""+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ litellm.get_model_info.cache_clear()+ expected = copy.deepcopy(litellm.get_model_info(model="anthropic/claude-sonnet-4-5"))++ router = litellm.Router(model_list=[])+ merged = router.get_router_model_info(+ deployment=Deployment(+ model_name="sonnet",+ litellm_params=LiteLLM_Params(model="claude-sonnet-4-5", custom_llm_provider="anthropic"),+ model_info=ModelInfo(id="sonnet-1"),+ ),+ received_model_name="sonnet",+ )++ assert litellm.get_model_info(model="anthropic/claude-sonnet-4-5") == expected+ for field in ("input_cost_per_token", "output_cost_per_token", "cache_read_input_token_cost"):+ assert merged[field] == expected[field]+++ def test_get_router_model_info_keeps_explicit_pricing_overrides():+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ litellm.get_model_info.cache_clear()+ router = litellm.Router(model_list=[])+ merged = router.get_router_model_info(+ deployment=Deployment(+ model_name="sonnet",+ litellm_params=LiteLLM_Params(model="claude-sonnet-4-5", custom_llm_provider="anthropic"),+ model_info=ModelInfo(id="sonnet-1", input_cost_per_token=1e-08),+ ),+ received_model_name="sonnet",+ )++ assert merged["input_cost_per_token"] == 1e-08+ assert litellm.get_model_info(model="anthropic/claude-sonnet-4-5")["input_cost_per_token"] != 1e-08+++ class TestModelGroupAliasReachesPreRoutingStrategies:+ """A `model_group_alias` whose target is a strategy router must dispatch exactly like the+ router's own model_name. The four strategy registries are keyed by the marker deployment's+ model_name, so the alias has to be resolved before the pre-routing hook looks anything up,+ and a group that resolves only to markers is not callable at all (LIT-4664)."""++ MARKER_TIMEOUT = 42.0+ REGISTRY_NAMES = ("auto_routers", "complexity_routers", "adaptive_routers", "quality_routers")++ class _RewriteStrategy:+ async def async_pre_routing_hook(+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False+ ):+ from litellm.types.router import PreRoutingHookResponse++ return PreRoutingHookResponse(model="gemini-flash", messages=messages)++ @classmethod+ def _router(cls, registry_name: str | None) -> "litellm.Router":+ from litellm.types.router import TaggedPreRoutingStrategy++ tiers = dict.fromkeys(("SIMPLE", "MEDIUM", "COMPLEX", "REASONING"), "gemini-flash")+ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-route",+ "litellm_params": {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {"tiers": tiers},+ "complexity_router_default_model": "gemini-flash",+ "timeout": cls.MARKER_TIMEOUT,+ },+ },+ {+ "model_name": "gemini-flash",+ "litellm_params": {"model": "gemini/gemini-3.6-flash", "mock_response": "routed by the tier"},+ },+ ],+ model_group_alias={"smart-alias": "smart-route"},+ )+ for name in cls.REGISTRY_NAMES:+ setattr(router, name, {})+ if registry_name is not None:+ setattr(+ router,+ registry_name,+ {"smart-route": [TaggedPreRoutingStrategy(tags=(), strategy=cls._RewriteStrategy())]},+ )+ return router++ @staticmethod+ def _messages() -> list[dict[str, str]]:+ return [{"role": "user", "content": "What is the capital of France?"}]++ @pytest.mark.parametrize("registry_name", REGISTRY_NAMES)+ @pytest.mark.asyncio+ async def test_alias_dispatches_to_the_strategy_registered_under_the_target(self, registry_name):+ router = self._router(registry_name)+ request_kwargs = {"metadata": {}}++ response = await router.async_pre_routing_hook(+ model="smart-alias", request_kwargs=request_kwargs, messages=self._messages()+ )++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_alias_call_still_forwards_the_marker_own_params_to_the_routed_tier(self):+ router = self._router("auto_routers")+ request_kwargs = {"metadata": {}}++ await router.async_pre_routing_hook(+ model="smart-alias", request_kwargs=request_kwargs, messages=self._messages()+ )++ assert request_kwargs["timeout"] == self.MARKER_TIMEOUT++ @pytest.mark.asyncio+ async def test_alias_deployment_selection_lands_on_the_tier_never_the_marker(self):+ router = self._router("auto_routers")++ deployment = await router.async_get_available_deployment(+ model="smart-alias", request_kwargs={"metadata": {}}, messages=self._messages()+ )++ assert deployment["litellm_params"]["model"] == "gemini/gemini-3.6-flash"++ @pytest.mark.asyncio+ async def test_alias_call_completes_and_still_bills_the_name_the_caller_sent(self):+ router = self._router("auto_routers")+ metadata: dict = {}++ response = await router.acompletion(+ model="smart-alias", messages=self._messages(), metadata=metadata+ )++ assert response.choices[0].message.content == "routed by the tier"+ assert metadata["model_group"] == "smart-alias"+ assert metadata["model_group_alias"] == "smart-alias"++ def test_a_group_of_only_markers_is_not_a_callable_model(self):+ router = self._router(None)++ with pytest.raises(litellm.BadRequestError, match="strategy router marker"):+ router.get_available_deployment(+ model="smart-route", messages=self._messages(), request_kwargs={"metadata": {}}+ )+++ @pytest.mark.usefixtures("local_model_cost_map")+ class TestAzureBaseModelFallbackLogging:+ """When an azure deployment has no base_model but its model name is a known+ azure key in the cost map, get_router_model_info resolves it via the+ fallback, so it must not log the per-request 'Could not identify azure+ model' ERROR. The ERROR must remain for genuinely unmappable deployment+ names. Issue #33172."""++ def _router_with_azure_deployment(self, deployment_model: str):+ return litellm.Router(+ model_list=[+ {+ "model_name": "my-group",+ "litellm_params": {+ "model": deployment_model,+ "api_key": "fake-key",+ "api_base": "https://fake.openai.azure.com",+ },+ "model_info": {"id": "azure-base-model-test-id"},+ }+ ]+ )++ def test_map_known_deployment_name_resolves_without_error_log(self):+ router = self._router_with_azure_deployment("azure/gpt-4o")++ with patch(+ "litellm.router.verbose_router_logger.error"+ ) as mock_error:+ model_info = router.get_router_model_info(+ deployment=None, received_model_name="my-group", id="azure-base-model-test-id"+ )++ assert not any(+ "Could not identify azure model" in str(call)+ for call in mock_error.call_args_list+ ), f"unexpected error log: {mock_error.call_args_list}"+ # the fallback resolution must actually surface the map values+ assert model_info["max_input_tokens"] == litellm.model_cost["azure/gpt-4o"]["max_input_tokens"]+ assert model_info["input_cost_per_token"] == litellm.model_cost["azure/gpt-4o"]["input_cost_per_token"]++ def test_unmappable_deployment_name_still_logs_error(self):+ router = self._router_with_azure_deployment("azure/my-custom-deployment-name")++ with patch(+ "litellm.router.verbose_router_logger.error"+ ) as mock_error:+ model_info = router.get_router_model_info(+ deployment=None, received_model_name="my-group", id="azure-base-model-test-id"+ )++ assert any(+ "Could not identify azure model" in str(call)+ for call in mock_error.call_args_list+ ), "expected the error log for an unmappable azure deployment name"+ # unmappable names resolve to a zeroed stub — unchanged behavior+ assert model_info.get("max_input_tokens") is None++ def test_explicit_base_model_still_wins(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "my-group",+ "litellm_params": {+ "model": "azure/some-deployment",+ "api_key": "fake-key",+ "api_base": "https://fake.openai.azure.com",+ },+ "model_info": {+ "id": "azure-base-model-test-id",+ "base_model": "azure/gpt-4o-mini",+ },+ }+ ]+ )++ model_info = router.get_router_model_info(+ deployment=None, received_model_name="my-group", id="azure-base-model-test-id"+ )+ assert model_info["max_input_tokens"] == litellm.model_cost["azure/gpt-4o-mini"]["max_input_tokens"]++ def test_model_group_info_intersects_supported_reasoning_efforts():+ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "anthropic/opus-like"},+ "model_info": {"id": "opus-like-deployment"},+ },+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "openai/mini-like"},+ "model_info": {"id": "mini-like-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ if model_id == "opus-like-deployment":+ return {+ "key": model_name,+ "litellm_provider": "anthropic",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_xhigh_reasoning_effort": True,+ "supports_max_reasoning_effort": True,+ }+ return {+ "key": model_name,+ "litellm_provider": "openai",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_none_reasoning_effort": False,+ "supports_minimal_reasoning_effort": True,+ "supports_xhigh_reasoning_effort": False,+ }++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="smart-group",+ user_facing_model_group_name="smart-group",+ )++ assert result is not None+ # opus-like offers all seven levels, mini-like lacks none/xhigh/max; only the common set survives,+ # so the group never advertises an effort routing could hand to a deployment that rejects it.+ assert result.supported_reasoning_efforts == ("minimal", "low", "medium", "high")+++ def test_model_group_info_reasoning_efforts_ignore_a_deployment_off_the_map():+ """The router fills every ModelInfo key, so a deployment absent from the model map arrives with+ supports_reasoning None rather than with the key missing. Its synthesized entry carries no mode,+ which is what separates it from a mapped non-reasoning model, and nothing being known about it is+ no reason to drop the levels the rest of the group agrees on."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "anthropic/opus-like"},+ "model_info": {"id": "opus-like-deployment"},+ },+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "openai/unmapped-model"},+ "model_info": {"id": "unmapped-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ if model_id == "opus-like-deployment":+ return {+ "key": model_name,+ "litellm_provider": "anthropic",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_max_reasoning_effort": True,+ }+ return {"key": model_name, "litellm_provider": "openai", "mode": None, "supports_reasoning": None}++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="smart-group",+ user_facing_model_group_name="smart-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == ("none", "minimal", "low", "medium", "high", "max")++++ def test_model_group_info_surfaces_supports_parallel_function_calling(local_model_cost_map):+ """``/model_group/info`` folds each deployment's registry flags into the group; a deployment whose+ registry entry declares parallel function calling must flip the group to True instead of False."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "glm-group",+ "litellm_params": {"model": "together_ai/zai-org/GLM-5.3-Flash", "api_key": "fake-key"},+ }+ ]+ )++ result = router._set_model_group_info(model_group="glm-group", user_facing_model_group_name="glm-group")++ assert result is not None+ assert result.supports_parallel_function_calling is True+++ def test_model_group_info_reasoning_efforts_empty_on_a_mapped_non_reasoning_deployment():+ """A group mixing a reasoning model with one the map knows is not a reasoning model shares no+ level, so it advertises none and the picker offers nothing rather than a level routing would+ hand to a deployment that rejects it."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "mixed-group",+ "litellm_params": {"model": "anthropic/opus-like"},+ "model_info": {"id": "opus-like-deployment"},+ },+ {+ "model_name": "mixed-group",+ "litellm_params": {"model": "openai/plain-chat"},+ "model_info": {"id": "plain-chat-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ if model_id == "opus-like-deployment":+ return {+ "key": model_name,+ "litellm_provider": "anthropic",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_max_reasoning_effort": True,+ }+ return {"key": model_name, "litellm_provider": "openai", "mode": "chat", "supports_reasoning": None}++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="mixed-group",+ user_facing_model_group_name="mixed-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == ()+++ def test_model_group_info_reasoning_efforts_ignore_a_value_declared_in_model_info():+ """The group's levels are computed from its deployments, so a value an operator left in one+ deployment's model_info must not seed them. Seeding let the first deployment read narrow the+ whole group while the same value on any other deployment was silently ignored."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "declared-group",+ "litellm_params": {"model": "openai/first-reasoner"},+ "model_info": {"id": "first-deployment"},+ },+ {+ "model_name": "declared-group",+ "litellm_params": {"model": "openai/second-reasoner"},+ "model_info": {"id": "second-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ info = {+ "key": model_name,+ "litellm_provider": "openai",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_none_reasoning_effort": True,+ }+ if model_id == "first-deployment":+ info["supported_reasoning_efforts"] = ("high",)+ return info++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="declared-group",+ user_facing_model_group_name="declared-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == ("none", "minimal", "low", "medium", "high")+++ def test_model_group_info_survives_a_junk_typed_operator_effort_value():+ """A deployment's registered model_info reads back with whatever the operator wrote under any+ key, so a wrong-typed supported_reasoning_efforts must not fail the group's info. Only the+ constructor's trailing override keeps the junk away from ModelGroupInfo validation."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "junk-declared-group",+ "litellm_params": {"model": "openai/lone-reasoner"},+ "model_info": {"id": "junk-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ return {+ "key": model_name,+ "litellm_provider": "openai",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_none_reasoning_effort": True,+ "supported_reasoning_efforts": "high",+ }++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="junk-declared-group",+ user_facing_model_group_name="junk-declared-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == ("none", "minimal", "low", "medium", "high")+++ def test_model_group_info_reasoning_efforts_ignore_a_mode_the_operator_declared():+ """A deployment is registered in the cost map under its own id with whatever model_info the+ operator wrote, so a mode they set themselves reads back exactly like one the map supplied. Only+ a mode the map supplied marks the deployment as known, or an off-map deployment carrying any+ mode empties the group it sits in."""+ from litellm.router_utils.reasoning_effort_capability import resolve_supported_reasoning_efforts++ mapped_model = "openai/gpt-5.6-sol"+ expected = resolve_supported_reasoning_efforts(+ litellm.get_model_info(model=mapped_model),+ deployment_is_mapped=True,+ )+ assert expected++ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-group",+ "litellm_params": {"model": mapped_model, "api_key": "sk-fake"},+ "model_info": {"id": "mapped-deployment"},+ },+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "openai/a-model-the-map-never-heard-of", "api_key": "sk-fake"},+ "model_info": {"id": "off-map-deployment", "mode": "chat"},+ },+ ]+ )++ result = router._set_model_group_info(+ model_group="smart-group",+ user_facing_model_group_name="smart-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == expected+++ class TestAddDeploymentApiBaseProviderResolution:+ def test_bare_model_with_known_api_base_initializes(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "groq-pinned",+ "litellm_params": {+ "model": "llama-3.3-70b-versatile",+ "api_base": "https://api.groq.com/openai/v1",+ "api_key": "fake-key",+ },+ },+ {+ "model_name": "deepseek-pinned",+ "litellm_params": {+ "model": "deepseek-chat",+ "api_base": "https://api.deepseek.com/v1",+ "api_key": "fake-key",+ },+ },+ ]+ )++ model_list = router.get_model_list()+ assert model_list is not None+ assert {m["model_name"] for m in model_list} == {"groq-pinned", "deepseek-pinned"}++ def test_bare_model_with_unknown_api_base_still_raises(self):+ with pytest.raises(litellm.BadRequestError, match="LLM Provider NOT provided"):+ litellm.Router(+ model_list=[+ {+ "model_name": "mystery",+ "litellm_params": {+ "model": "some-unknown-model",+ "api_base": "https://llm.internal.example.com/v1",+ "api_key": "fake-key",+ },+ }+ ]+ )++ def test_explicit_custom_llm_provider_beats_api_base_endpoint_match(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "openai-via-gateway",+ "litellm_params": {+ "model": "gpt-3.5-turbo",+ "custom_llm_provider": "openai",+ "api_base": "https://api.groq.com/openai/v1",+ "api_key": "fake-key",+ },+ }+ ]+ )++ deployment = router.get_deployment_by_model_group_name("openai-via-gateway")+ assert deployment is not None+ assert deployment.litellm_params.custom_llm_provider == "openai"++ # =====================================================================+ # anthropic_messages mid-stream-fallback helpers, added for #24004+ # (mid-stream fallback not supported for anthropic_messages route type).+ #+ # anthropic_messages goes through _ageneric_api_call_with_fallbacks rather+ # than _acompletion, so its returned iterator was never wrapped by the chat+ # completions fallback handler: an SSE `event: error` frame from a native+ # Anthropic/Bedrock passthrough passed through to the client silently, and a+ # MidStreamFallbackError raised by the completion-bridge path's+ # CustomStreamWrapper (e.g. a Vertex AI transport drop) propagated+ # unhandled.+ #+ # Targets the helpers introduced on Router:+ # - _aanthropic_messages_streaming_iterator+ # - _aanthropic_messages_fallback_attempt+ # - _aanthropic_messages_with_streaming_fallbacks+ # - _dispatch_generic_call_type+ # =====================================================================+++ async def _anthropic_messages_empty_generator():+ return+ yield # pragma: no cover - makes this an async generator+++ def _anthropic_messages_make_wrapper() -> FallbackAwareAnthropicMessagesStream:+ """A minimal wrapper for tests that call _aanthropic_messages_fallback_attempt+ directly, bypassing _aanthropic_messages_streaming_iterator."""+ return FallbackAwareAnthropicMessagesStream(_anthropic_messages_empty_generator(), object())+++ def _anthropic_messages_make_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "primary",+ "litellm_params": {+ "model": "anthropic/claude-sonnet-4-5",+ "api_key": "sk-test",+ },+ },+ {+ "model_name": "fallback",+ "litellm_params": {+ "model": "bedrock/anthropic.claude-sonnet-4-5",+ },+ },+ ]+ )+++ class _AnthropicMessagesFakeByteStream:+ """Minimal AsyncIterator[bytes], carrying _hidden_params like+ AnthropicMessagesStreamingResponse does."""++ def __init__(self, chunks: list) -> None:+ self._chunks = list(chunks)+ self._hidden_params = {"additional_headers": {"x-amzn-requestid": "req-1"}}+ self.closed = False++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ if not self._chunks:+ raise StopAsyncIteration+ return self._chunks.pop(0)++ async def aclose(self) -> None:+ self.closed = True+++ class _AnthropicMessagesRaisingByteStream:+ """Simulates the completion-bridge path: no error SSE chunk is ever+ yielded, the underlying CustomStreamWrapper raises MidStreamFallbackError+ directly out of the iterator instead (a Vertex AI transport drop)."""++ def __init__(self, chunks: list, error: Exception) -> None:+ self._chunks = list(chunks)+ self._error = error+ self._hidden_params: dict = {}+ self.closed = False++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ if self._chunks:+ return self._chunks.pop(0)+ raise self._error++ async def aclose(self) -> None:+ self.closed = True+++ class _AnthropicMessagesFallbackByteStream:+ def __init__(self, chunks: list, hidden_params: dict | None = None) -> None:+ self._chunks = list(chunks)+ self._hidden_params = hidden_params if hidden_params is not None else {}++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ if not self._chunks:+ raise StopAsyncIteration+ return self._chunks.pop(0)+++ def _anthropic_messages_overloaded_error_chunk() -> bytes:+ return (+ b"event: error\n"+ b'data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}\n\n'+ )+++ def _anthropic_messages_invalid_request_error_chunk() -> bytes:+ return (+ b"event: error\n"+ b'data: {"type": "error", "error": {"type": "invalid_request_error", "message": "bad request"}}\n\n'+ )+++ def _anthropic_messages_rate_limit_error_chunk() -> bytes:+ return (+ b"event: error\n"+ b'data: {"type": "error", "error": {"type": "rate_limit_error", "message": "Too many requests"}}\n\n'+ )+++ def _anthropic_messages_content_chunk(text: str = "hi") -> bytes:+ payload = f'{{"type": "content_block_delta", "delta": {{"type": "text_delta", "text": "{text}"}}}}'+ return f"event: content_block_delta\ndata: {payload}\n\n".encode()+++ def _anthropic_messages_message_start_chunk() -> bytes:+ """A lifecycle/bookkeeping frame Anthropic sends before any real content -+ routinely the very first event before an overload error."""+ return b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_1"}}\n\n'+++ def _anthropic_messages_ping_chunk() -> bytes:+ return b'event: ping\ndata: {"type": "ping"}\n\n'+++ # -------- _aanthropic_messages_streaming_iterator (passthrough) --------+++ @pytest.mark.asyncio+ async def test_anthropic_messages_streaming_iterator_passthrough():+ """Without any error chunk, the wrapper forwards every chunk unchanged+ and carries the source iterator's _hidden_params through (so response+ headers like Bedrock's request-id keep flowing to the client)."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_content_chunk("hi"), _anthropic_messages_content_chunk(" there")]+ )++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )++ collected = [chunk async for chunk in wrapped]+ assert collected == [_anthropic_messages_content_chunk("hi"), _anthropic_messages_content_chunk(" there")]+ assert wrapped._hidden_params["additional_headers"]["x-amzn-requestid"] == "req-1"+++ @pytest.mark.asyncio+ async def test_anthropic_messages_streaming_iterator_flushes_buffered_lifecycle_frames_in_order():+ """Regression: lifecycle frames held back to guard against a mid-stream+ fallback must still reach the client, in order, once real content+ arrives - buffering them for the fallback-safety check must not silently+ drop them on the happy path."""+ router = _anthropic_messages_make_router()+ message_stop = b'event: message_stop\ndata: {"type": "message_stop"}\n\n'+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("hi"), message_stop]+ )++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )++ collected = [chunk async for chunk in wrapped]+ assert collected == [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("hi"), message_stop]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_streaming_iterator_flushes_buffered_frames_on_stream_end():+ """Regression: if the primary stream ends with only lifecycle frames and+ no content and no error, the buffered frames must still reach the+ client rather than being silently swallowed."""+ router = _anthropic_messages_make_router()+ message_stop = b'event: message_stop\ndata: {"type": "message_stop"}\n\n'+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_message_start_chunk(), message_stop])++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )++ collected = [chunk async for chunk in wrapped]+ assert collected == [_anthropic_messages_message_start_chunk(), message_stop]++ with pytest.raises(StopAsyncIteration):+ await wrapped.__anext__()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_content_coalesced_with_error_in_one_physical_chunk_skips_fallback():+ """Greptile review round: transport-level buffering can coalesce a real+ content_block_delta and a following retriable error into ONE physical+ read from the source iterator. Since the whole chunk (content and error+ together) is forwarded to the client atomically, the client genuinely+ receives the content - so no fallback must be attempted, exactly as if+ the two events had arrived as separate reads."""+ router = _anthropic_messages_make_router()+ coalesced_chunk = _anthropic_messages_content_chunk("partial") + _anthropic_messages_overloaded_error_chunk()+ source = _AnthropicMessagesFakeByteStream([coalesced_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=_AnthropicMessagesFallbackByteStream([])),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [coalesced_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_ping_behind_buffered_lifecycle_frame_is_dropped():+ """Bugbot regression: a `ping` keepalive behind buffered lifecycle frames+ carries no content and is dropped outright rather than buffered -+ otherwise a slow-starting connection sending many pings could grow the+ pre-content buffer without bound."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [+ _anthropic_messages_message_start_chunk(),+ _anthropic_messages_ping_chunk(),+ _anthropic_messages_content_chunk("hi"),+ ]+ )++ wrapped = await router._aanthropic_messages_streaming_iterator(response=source, initial_kwargs={"model": "primary"})+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("hi")]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_leading_ping_keepalive_is_forwarded_live():+ """A `ping` that no lifecycle frame precedes is how a hold-back turn keeps+ its connection alive (AgenticAnthropicStreamingIterator), so it must reach+ the client at once rather than wait behind the pre-content buffer."""+ router = _anthropic_messages_make_router()+ content_released = asyncio.Event()++ async def source():+ yield _anthropic_messages_ping_chunk()+ await content_released.wait()+ yield _anthropic_messages_message_start_chunk()+ yield _anthropic_messages_content_chunk("hi")++ wrapped = await router._aanthropic_messages_streaming_iterator(response=source(), initial_kwargs={"model": "primary"})++ assert await asyncio.wait_for(wrapped.__anext__(), timeout=1) == _anthropic_messages_ping_chunk()+ content_released.set()+ assert [chunk async for chunk in wrapped] == [+ _anthropic_messages_message_start_chunk(),+ _anthropic_messages_content_chunk("hi"),+ ]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_leading_ping_does_not_disqualify_fallback():+ """A live-forwarded leading `ping` commits nothing: a retriable error after+ it still falls back, and the fallback's own lifecycle follows the ping cleanly."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_ping_chunk(), _anthropic_messages_overloaded_error_chunk()]+ )+ fallback_message_start = b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_2"}}\n\n'+ fallback_stream = _AnthropicMessagesFallbackByteStream(+ [fallback_message_start, _anthropic_messages_content_chunk("fallback answer")]+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [+ _anthropic_messages_ping_chunk(),+ fallback_message_start,+ _anthropic_messages_content_chunk("fallback answer"),+ ]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_hold_back_retrieval_failure_reaches_client_without_fallback():+ """The hold-back iterator's own retrieval-failure frame is the gateway's verdict, not a+ provider failure: a configured fallback stays untouched and the client reads the error+ right after the live keepalive."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_ping_chunk(), SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES]+ )+ fallback = AsyncMock(+ return_value=_AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])+ )++ with patch.object(router, "async_function_with_fallbacks_common_utils", new=fallback):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ fallback.assert_not_called()+ assert collected == [_anthropic_messages_ping_chunk(), SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_pre_content_buffer_cap_forces_commit():+ """Bugbot regression: a hostile or pathological upstream that never emits+ real content or an error must not grow the pre-content lifecycle buffer+ without bound - hitting MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS commits+ to the primary stream early, exactly as real content arriving would."""+ router = _anthropic_messages_make_router()+ lifecycle_chunk = _anthropic_messages_message_start_chunk()+ error_chunk = _anthropic_messages_overloaded_error_chunk()+ chunks = [lifecycle_chunk] * (MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS + 5) + [error_chunk]+ source = _AnthropicMessagesFakeByteStream(chunks)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=_AnthropicMessagesFallbackByteStream([])),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )+ collected = [chunk async for chunk in wrapped]++ mock_fallback.assert_not_awaited()+ assert collected.count(lifecycle_chunk) == MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS + 5+ assert collected[-1] == error_chunk+++ @pytest.mark.asyncio+ async def test_anthropic_messages_ping_coalesced_with_content_in_one_physical_chunk_is_forwarded():+ """Greptile/Bugbot regression: transport-level buffering can coalesce a+ `ping` keepalive and a real content_block_delta into ONE physical read.+ The pre-content ping-drop must only discard PURE ping frames - dropping+ the whole coalesced chunk would silently lose generated content."""+ router = _anthropic_messages_make_router()+ coalesced_chunk = _anthropic_messages_ping_chunk() + _anthropic_messages_content_chunk("hi")+ source = _AnthropicMessagesFakeByteStream([coalesced_chunk])++ wrapped = await router._aanthropic_messages_streaming_iterator(response=source, initial_kwargs={"model": "primary"})+ collected = [chunk async for chunk in wrapped]++ assert collected == [coalesced_chunk]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_ping_coalesced_with_retriable_error_still_falls_back():+ """Greptile/Bugbot regression: a physical chunk coalescing a `ping` with a+ retriable `event: error` must not be discarded as a keepalive - the error+ inside it must still trigger the mid-stream fallback."""+ router = _anthropic_messages_make_router()+ coalesced_chunk = _anthropic_messages_ping_chunk() + _anthropic_messages_overloaded_error_chunk()+ source = _AnthropicMessagesFakeByteStream([coalesced_chunk])+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )+ collected = [chunk async for chunk in wrapped]++ mock_fallback.assert_awaited_once()+ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+++ # -------- _aanthropic_messages_fallback_attempt --------+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_yields_fallback_stream():+ """Direct-call regression: the fallback-attempt helper re-enters the+ Router's fallback chain and forwards whatever the fallback produces."""+ router = _anthropic_messages_make_router()+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ collected = [+ chunk+ async for chunk in router._aanthropic_messages_fallback_attempt(+ error,+ {"model": "primary", "messages": [{"role": "user", "content": "hi"}]},+ _anthropic_messages_make_wrapper(),+ )+ ]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ assert mock_fallback.await_args.kwargs["e"] is error+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_raises_original_exception_on_double_failure():+ """Direct-call regression: when the fallback attempt itself fails with a+ MidStreamFallbackError wrapping a real provider exception, that real+ exception must surface rather than the internal wrapper exception."""+ router = _anthropic_messages_make_router()+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")+ original_exception = litellm.APIError(+ status_code=503, message="fallback also overloaded", llm_provider="bedrock", model="fallback"+ )+ fallback_failure = MidStreamFallbackError(+ message="fallback failed", model="fallback", llm_provider="bedrock", original_exception=original_exception+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(side_effect=fallback_failure),+ ):+ with pytest.raises(litellm.APIError) as exc_info:+ async for _ in router._aanthropic_messages_fallback_attempt(+ error, {"model": "primary"}, _anthropic_messages_make_wrapper()+ ):+ pass++ assert exc_info.value is original_exception+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_yields_non_streaming_fallback_response():+ """Bugbot regression: a fallback that resolves to a non-streaming+ response (no __aiter__, e.g. an agentic tool-use interception loop) must+ be synthesized into a valid SSE byte sequence, not yielded as a raw dict+ into a byte stream - the generator is typed AsyncGenerator[bytes, None]+ and every item reaching the client must be a real SSE frame."""+ router = _anthropic_messages_make_router()+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")+ non_streaming_response = {"id": "msg_1", "type": "message", "content": [{"type": "text", "text": "hi"}]}++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=non_streaming_response),+ ):+ collected = [+ item+ async for item in router._aanthropic_messages_fallback_attempt(+ error, {"model": "primary"}, _anthropic_messages_make_wrapper()+ )+ ]++ assert all(isinstance(item, bytes) for item in collected)+ event_types = [item.split(b"\n")[0].removeprefix(b"event: ") for item in collected]+ assert event_types == [+ b"message_start",+ b"content_block_start",+ b"content_block_delta",+ b"content_block_stop",+ b"message_delta",+ b"message_stop",+ ]+ assert b'"text": "hi"' in collected[2]+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_reraises_plain_exception_on_double_failure():+ """Direct-call regression: when the fallback attempt fails with a plain+ exception (not a MidStreamFallbackError), that exception itself must+ propagate unchanged."""+ router = _anthropic_messages_make_router()+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")+ fallback_failure = ValueError("no healthy deployments")++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(side_effect=fallback_failure),+ ):+ with pytest.raises(ValueError, match="no healthy deployments") as exc_info:+ async for _ in router._aanthropic_messages_fallback_attempt(+ error, {"model": "primary"}, _anthropic_messages_make_wrapper()+ ):+ pass++ assert exc_info.value is fallback_failure+++ # -------- _aanthropic_messages_with_streaming_fallbacks --------+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_non_streaming_passthrough():+ """A non-streaming response (plain dict) is returned unchanged, never wrapped."""+ router = _anthropic_messages_make_router()+ plain_response = {"id": "msg_1", "type": "message"}++ async def fake_original(**_kwargs):+ return plain_response++ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(return_value=plain_response),+ ):+ out = await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=False,+ )+ assert out is plain_response+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_wraps_streaming_iterator():+ """A streaming response is wrapped via _aanthropic_messages_streaming_iterator."""+ router = _anthropic_messages_make_router()+ streaming_iter = _AnthropicMessagesFakeByteStream([_anthropic_messages_content_chunk()])+ wrapped_marker = object()++ async def fake_original(**_kwargs):+ return streaming_iter++ with (+ patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(return_value=streaming_iter),+ ),+ patch.object(+ router,+ "_aanthropic_messages_streaming_iterator",+ new=AsyncMock(return_value=wrapped_marker),+ ) as mock_wrap,+ ):+ out = await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=True,+ )+ assert out is wrapped_marker+ mock_wrap.assert_awaited_once()+++ # -------- mid-stream error handling --------+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_on_pre_first_chunk_error_event():+ """Regression for #24004: a retriable SSE `event: error` frame+ (overloaded_error/internal_server_error) that arrives before any real+ content must trigger the router's fallback chain instead of passing+ through to the client silently."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_overloaded_error_chunk()])+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary", "messages": [{"role": "user", "content": "hi"}]},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ raised = mock_fallback.await_args.kwargs["e"]+ assert isinstance(raised, MidStreamFallbackError)+ assert raised.status_code == 503+ assert raised.is_pre_first_chunk is True+ assert source.closed is True+++ @pytest.mark.asyncio+ async def test_anthropic_messages_mid_stream_error_preserves_real_status_code():+ """Bugbot regression: the MidStreamFallbackError raised for a detected SSE+ `event: error` frame must carry the error's REAL parsed status code+ (via original_exception), not silently default to 503 for every error+ type - a rate_limit_error (429) must surface as 429, not 503."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_rate_limit_error_chunk()])+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary", "messages": [{"role": "user", "content": "hi"}]},+ )+ [chunk async for chunk in wrapped]++ raised = mock_fallback.await_args.kwargs["e"]+ assert isinstance(raised, MidStreamFallbackError)+ assert raised.status_code == 429+ assert raised.original_exception is not None+ assert raised.original_exception.status_code == 429+ assert raised.original_exception.llm_provider == "anthropic"+++ def test_merge_fallback_hidden_params_direct_call():+ """Direct-call regression: merge_fallback_hidden_params combines the+ fallback's hidden params/headers with whatever was already present,+ with the fallback's values winning on key collisions."""+ wrapper = FallbackAwareAnthropicMessagesStream(+ _anthropic_messages_empty_generator(),+ _AnthropicMessagesFakeByteStream([]), # carries {"additional_headers": {"x-amzn-requestid": "req-1"}}+ )+ wrapper.merge_fallback_hidden_params(+ {"model_id": "fallback-deployment"},+ {"x-amzn-requestid": "req-2", "x-fallback-only": "yes"},+ )+ assert wrapper._hidden_params["model_id"] == "fallback-deployment"+ assert wrapper._hidden_params["additional_headers"] == {+ "x-amzn-requestid": "req-2",+ "x-fallback-only": "yes",+ }+++ def test_anthropic_stream_should_drop_pre_content_ping_direct_call():+ ping = _anthropic_messages_ping_chunk()+ content = _anthropic_messages_content_chunk("hi")+ assert _anthropic_stream_should_drop_pre_content_ping(ping, has_generated_content=False) is True+ assert _anthropic_stream_should_drop_pre_content_ping(ping, has_generated_content=True) is False+ assert _anthropic_stream_should_drop_pre_content_ping(content, has_generated_content=False) is False+++ def test_anthropic_stream_forwards_ping_live_direct_call():+ ping = _anthropic_messages_ping_chunk()+ content = _anthropic_messages_content_chunk("hi")+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=False, buffered_chunk_count=0) is True+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=False, buffered_chunk_count=1) is False+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=True, buffered_chunk_count=0) is False+ assert _anthropic_stream_forwards_ping_live(content, has_generated_content=False, buffered_chunk_count=0) is False+++ def test_anthropic_stream_error_is_gateway_verdict_direct_call():+ assert _anthropic_stream_error_is_gateway_verdict(SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES) is True+ assert _anthropic_stream_error_is_gateway_verdict(_anthropic_messages_overloaded_error_chunk()) is False+ assert _anthropic_stream_error_is_gateway_verdict(_anthropic_messages_ping_chunk()) is False+++ def test_fallback_aware_stream_reports_withheld_output_of_its_current_source():+ """The proxy's cancel-refund guard reads this flag off the router wrapper, so it+ must reflect the stream actually being drained: the primary, then the fallback."""++ class _HoldingBack:+ _hidden_params = {"additional_headers": {}}+ has_buffered_provider_output = True++ wrapper = FallbackAwareAnthropicMessagesStream(_anthropic_messages_empty_generator(), _HoldingBack())+ assert wrapper.has_buffered_provider_output is True++ wrapper.adopt_fallback_source(_AnthropicMessagesFakeByteStream([]))+ assert wrapper.has_buffered_provider_output is False+++ def test_is_retriable_anthropic_status_direct_call():+ assert _is_retriable_anthropic_status(429) is True+ assert _is_retriable_anthropic_status(503) is True+ assert _is_retriable_anthropic_status(500) is True+ assert _is_retriable_anthropic_status(400) is False+ assert _is_retriable_anthropic_status(404) is False+++ def test_anthropic_stream_should_decline_fallback_direct_call():+ pre_first_chunk_error = MidStreamFallbackError(+ message="overloaded", model="primary", llm_provider="anthropic", is_pre_first_chunk=True+ )+ post_first_chunk_error = MidStreamFallbackError(+ message="overloaded", model="primary", llm_provider="anthropic", is_pre_first_chunk=False+ )+ assert _anthropic_stream_should_decline_fallback(False, pre_first_chunk_error) is False+ assert _anthropic_stream_should_decline_fallback(True, pre_first_chunk_error) is True+ assert _anthropic_stream_should_decline_fallback(False, post_first_chunk_error) is True+++ def test_anthropic_stream_commits_now_direct_call():+ content = _anthropic_messages_content_chunk("hi")+ lifecycle_chunk = _anthropic_messages_message_start_chunk()+ assert _anthropic_stream_commits_now(content, has_generated_content=False, buffered_chunk_count=0) is True+ assert _anthropic_stream_commits_now(content, has_generated_content=True, buffered_chunk_count=0) is False+ assert (+ _anthropic_stream_commits_now(+ lifecycle_chunk,+ has_generated_content=False,+ buffered_chunk_count=MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS,+ )+ is True+ )+ assert (+ _anthropic_stream_commits_now(+ lifecycle_chunk,+ has_generated_content=False,+ buffered_chunk_count=MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS - 1,+ )+ is False+ )+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_merges_fallback_hidden_params():+ """Bugbot regression: after a successful mid-stream fallback, the+ wrapper's _hidden_params must reflect the FALLBACK deployment's own+ provider headers (e.g. a different Bedrock request-id), not stay+ frozen on the primary's - raw bytes can't carry per-item _hidden_params+ the way a ModelResponseStream/ResponsesAPI event can, so the wrapper+ itself is the only place left to expose them."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_overloaded_error_chunk()]+ ) # carries x-amzn-requestid: req-1+ fallback_stream = _AnthropicMessagesFallbackByteStream(+ [_anthropic_messages_content_chunk("fallback answer")],+ hidden_params={"additional_headers": {"x-amzn-requestid": "req-2", "x-fallback-only": "yes"}},+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ _ = [chunk async for chunk in wrapped]++ headers = wrapped._hidden_params["additional_headers"]+ assert headers["x-amzn-requestid"] == "req-2"+ assert headers["x-fallback-only"] == "yes"+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_deep_copies_nested_metadata():+ """Bugbot regression: a shallow .copy() of kwargs still shares the+ nested litellm_metadata/metadata dict objects with the primary attempt.+ _update_kwargs_with_deployment mutates that dict in place with+ deployment-specific fields, which must not leak into the fallback+ request's metadata."""+ router = _anthropic_messages_make_router()+ primary_metadata = {"model_group": "primary"}+ streaming_iter_kwargs = {}++ async def fake_original(**_kwargs):+ # Simulate _update_kwargs_with_deployment mutating the primary's+ # litellm_metadata in place, as the real helper does.+ primary_metadata["deployment"] = "primary-deployment-object"+ return _AnthropicMessagesFakeByteStream([_anthropic_messages_content_chunk("hi")])++ with patch.object(+ router,+ "_aanthropic_messages_streaming_iterator",+ new=AsyncMock(side_effect=lambda **kwargs: streaming_iter_kwargs.update(kwargs) or "wrapped"),+ ):+ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(side_effect=fake_original),+ ):+ await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=True,+ litellm_metadata=primary_metadata,+ )++ fallback_kwargs = streaming_iter_kwargs["initial_kwargs"]+ assert fallback_kwargs["litellm_metadata"] is not primary_metadata+ assert "deployment" not in fallback_kwargs["litellm_metadata"]+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_deep_copies_metadata_field():+ """Same regression as above for the (separate) `metadata` kwarg some+ call sites use instead of `litellm_metadata`."""+ router = _anthropic_messages_make_router()+ primary_metadata = {"tag": "primary"}+ streaming_iter_kwargs = {}++ async def fake_original(**_kwargs):+ primary_metadata["deployment"] = "primary-deployment-object"+ return _AnthropicMessagesFakeByteStream([_anthropic_messages_content_chunk("hi")])++ with patch.object(+ router,+ "_aanthropic_messages_streaming_iterator",+ new=AsyncMock(side_effect=lambda **kwargs: streaming_iter_kwargs.update(kwargs) or "wrapped"),+ ):+ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(side_effect=fake_original),+ ):+ await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=True,+ metadata=primary_metadata,+ )++ fallback_kwargs = streaming_iter_kwargs["initial_kwargs"]+ assert fallback_kwargs["metadata"] is not primary_metadata+ assert "deployment" not in fallback_kwargs["metadata"]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_triggers_after_lifecycle_only_frame():+ """Regression: Anthropic routinely sends a message_start lifecycle frame+ before an overload error even fires. A lifecycle-only frame (no real+ content) must not disqualify the fallback attempt, and must not reach+ the client either - forwarding it and then appending the fallback's own+ message_start would produce two overlapping message lifecycles on one+ SSE stream. The primary's buffered lifecycle frame is discarded and the+ client sees only the fallback's own, single, clean lifecycle."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_message_start_chunk(), _anthropic_messages_overloaded_error_chunk()]+ )+ fallback_message_start = b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_2"}}\n\n'+ fallback_stream = _AnthropicMessagesFallbackByteStream(+ [fallback_message_start, _anthropic_messages_content_chunk("fallback answer")]+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [fallback_message_start, _anthropic_messages_content_chunk("fallback answer")]+ assert collected.count(_anthropic_messages_message_start_chunk()) == 0, (+ "the primary's message_start must never reach the client"+ )+ assert sum(1 for c in collected if c.startswith(b"event: message_start")) == 1, (+ "exactly one message_start must reach the client"+ )+ mock_fallback.assert_awaited_once()+ raised = mock_fallback.await_args.kwargs["e"]+ assert raised.is_pre_first_chunk is True+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_error_after_real_content_does_not_restart_stream():+ """Regression: a MidStreamFallbackError raised directly by the source+ iterator (the completion-bridge path's CustomStreamWrapper, e.g. a+ transport drop) must not trigger a fallback once real content already+ reached the client - that would append a second, overlapping message+ lifecycle onto the same SSE stream. The original exception must+ propagate to the caller instead."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ original_exception = litellm.APIError(+ status_code=503,+ message="stream reset",+ llm_provider="vertex_ai",+ model="primary",+ )+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ original_exception=original_exception,+ is_pre_first_chunk=False,+ )+ source = _AnthropicMessagesRaisingByteStream([content], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(litellm.APIError) as exc_info:+ await _consume()++ assert collected == [content]+ assert exc_info.value is original_exception+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_also_catches_raised_midstream_error():+ """Regression for the completion-bridge path (deployments with no native+ /v1/messages endpoint): its CustomStreamWrapper raises+ MidStreamFallbackError directly (e.g. on a Vertex AI transport drop)+ instead of yielding an SSE error chunk - the wrapper must catch that too."""+ router = _anthropic_messages_make_router()+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ is_pre_first_chunk=True,+ )+ source = _AnthropicMessagesRaisingByteStream([], raised_error)+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ assert mock_fallback.await_args.kwargs["e"] is raised_error+++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "raised_error",+ [+ BedrockError(status_code=503, message='serviceUnavailableException {"message": "Service unavailable"}'),+ BedrockError(status_code=500, message='internalServerException {"message": "Internal error"}'),+ BedrockError(status_code=429, message='throttlingException {"message": "Too many requests"}'),+ httpx.ReadError("connection reset by upstream"),+ ],+ ids=["503", "500", "429", "transport-drop"],+ )+ async def test_anthropic_messages_raised_provider_error_before_content_triggers_fallback(raised_error):+ """A retriable raise before content falls over exactly like a detected SSE error event."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesRaisingByteStream([_anthropic_messages_message_start_chunk()], raised_error)+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ converted = mock_fallback.await_args.kwargs["e"]+ assert isinstance(converted, MidStreamFallbackError)+ assert converted.original_exception is raised_error+ assert converted.is_pre_first_chunk is True+ assert source.closed is True+++ class _AnthropicMessagesStringStatusError(Exception):+ def __init__(self):+ super().__init__("bad request")+ self.status_code = "400"+++ class _AnthropicMessagesResponseOnlyStatusError(Exception):+ def __init__(self):+ super().__init__("bad request")+ self.response = SimpleNamespace(status_code=400)+++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "raised_error",+ [+ BedrockError(status_code=400, message='validationException {"message": "Malformed input"}'),+ BedrockError(status_code=424, message='modelStreamErrorException {"message": "Model stream error"}'),+ _AnthropicMessagesStringStatusError(),+ _AnthropicMessagesResponseOnlyStatusError(),+ ],+ ids=["400", "424", "str-400", "response-only-400"],+ )+ async def test_anthropic_messages_raised_non_retriable_provider_error_propagates_unchanged(raised_error):+ """A raised client error reaches the caller as the same exception, nothing flushed, no fallback."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesRaisingByteStream([_anthropic_messages_message_start_chunk()], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(type(raised_error)) as exc_info:+ await _consume()++ assert collected == []+ assert exc_info.value is raised_error+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_provider_error_after_content_propagates_unchanged():+ """A raise after content propagates unchanged even when its status is retriable."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ raised_error = BedrockError(+ status_code=503, message='serviceUnavailableException {"message": "Service unavailable"}'+ )+ source = _AnthropicMessagesRaisingByteStream([content], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(BedrockError) as exc_info:+ await _consume()++ assert collected == [content]+ assert exc_info.value is raised_error+ mock_fallback.assert_not_awaited()+++ @pytest.mark.parametrize(+ "error, expected_status",+ [+ (BedrockError(status_code=503, message="unavailable"), 503),+ (_AnthropicMessagesStringStatusError(), 400),+ (_AnthropicMessagesResponseOnlyStatusError(), 400),+ (httpx.ReadError("connection reset by upstream"), None),+ ],+ ids=["int", "digit-str", "response-only", "none"],+ )+ def test_anthropic_stream_raised_error_status_reads_every_status_shape(error, expected_status):+ assert _anthropic_stream_raised_error_status(error) == expected_status+++ @pytest.mark.parametrize(+ "error, has_generated_content, converts",+ [+ (BedrockError(status_code=503, message="unavailable"), False, True),+ (httpx.ReadError("connection reset by upstream"), False, True),+ (BedrockError(status_code=400, message="malformed"), False, False),+ (BedrockError(status_code=503, message="unavailable"), True, False),+ ],+ ids=["retriable", "no-status", "client-error", "after-content"],+ )+ def test_anthropic_stream_fallback_error_for_raised_gates_like_a_detected_error_event(+ error, has_generated_content, converts+ ):+ converted = _anthropic_stream_fallback_error_for_raised(error, "primary", has_generated_content)+ if not converts:+ assert converted is None+ return+ assert isinstance(converted, MidStreamFallbackError)+ assert converted.original_exception is error+ assert converted.is_pre_first_chunk is True+ assert converted.llm_provider == "anthropic"+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_recover_stream_error_flushes_buffered_frames_before_declining():+ router = _anthropic_messages_make_router()+ original = BedrockError(status_code=503, message="unavailable")+ declined = MidStreamFallbackError(+ message="unavailable",+ model="primary",+ llm_provider="anthropic",+ original_exception=original,+ is_pre_first_chunk=False,+ )+ buffered = (_anthropic_messages_message_start_chunk(),)+ flushed = []++ async def drain(recovery) -> None:+ async for chunk in recovery:+ flushed.append(chunk)++ with patch.object(router, "_aanthropic_messages_fallback_attempt") as mock_attempt:+ recovery = router._aanthropic_messages_recover_stream_error(+ declined, True, buffered, "primary", {"model": "primary"}, _anthropic_messages_make_wrapper()+ )+ with pytest.raises(BedrockError) as exc_info:+ await drain(recovery)+ assert flushed == list(buffered)+ assert exc_info.value is original+ mock_attempt.assert_not_called()+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_recover_stream_error_hands_converted_raise_to_fallback_attempt():+ router = _anthropic_messages_make_router()+ raised = BedrockError(status_code=503, message="unavailable")+ handed_over = []++ async def fake_attempt(fallback_error, initial_kwargs, wrapper):+ handed_over.append(fallback_error)+ yield b"fallback"++ with patch.object(router, "_aanthropic_messages_fallback_attempt", new=fake_attempt):+ recovery = router._aanthropic_messages_recover_stream_error(+ raised, False, (), "primary", {"model": "primary"}, _anthropic_messages_make_wrapper()+ )+ collected = [chunk async for chunk in recovery]+ assert collected == [b"fallback"]+ assert len(handed_over) == 1+ assert isinstance(handed_over[0], MidStreamFallbackError)+ assert handed_over[0].original_exception is raised+++ @pytest.mark.asyncio+ async def test_anthropic_messages_non_retriable_client_error_skips_fallback():+ """A 4xx (non-429) error type (e.g. invalid_request_error) is a client+ error a fallback attempt cannot fix, so it must be forwarded to the+ client as-is rather than burning a fallback attempt."""+ router = _anthropic_messages_make_router()+ error_chunk = _anthropic_messages_invalid_request_error_chunk()+ source = _AnthropicMessagesFakeByteStream([error_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [error_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_post_first_chunk_error_skips_fallback():+ """Once content has already reached the caller, retrying would start a+ second, overlapping Anthropic message lifecycle on the same SSE stream -+ the error must be forwarded instead of triggering an invisible retry."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ error_chunk = _anthropic_messages_overloaded_error_chunk()+ source = _AnthropicMessagesFakeByteStream([content, error_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [content, error_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_non_retriable_error_flushes_buffered_lifecycle_frames():+ """A non-retriable error arriving while lifecycle frames are still+ buffered (no content seen yet) must flush those buffered frames before+ forwarding the error, so the client still sees the whole primary+ attempt rather than losing the buffered message_start silently."""+ router = _anthropic_messages_make_router()+ error_chunk = _anthropic_messages_invalid_request_error_chunk()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_message_start_chunk(), error_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_message_start_chunk(), error_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_error_declined_flushes_buffered_lifecycle_frames():+ """When a raised MidStreamFallbackError is declined (source says content+ was not pre-first-chunk) while lifecycle frames are still buffered, they+ must be flushed to the client before the exception propagates."""+ router = _anthropic_messages_make_router()+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ is_pre_first_chunk=False,+ )+ source = _AnthropicMessagesRaisingByteStream([_anthropic_messages_message_start_chunk()], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(MidStreamFallbackError) as exc_info:+ await _consume()++ assert collected == [_anthropic_messages_message_start_chunk()]+ assert exc_info.value is raised_error+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_error_without_original_exception_reraises_itself():+ """When a declined MidStreamFallbackError carries no original_exception,+ the bare exception itself must propagate rather than being swallowed."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ is_pre_first_chunk=False,+ )+ source = _AnthropicMessagesRaisingByteStream([content], raised_error)++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(MidStreamFallbackError) as exc_info:+ await _consume()++ assert collected == [content]+ assert exc_info.value is raised_error+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_also_failing_raises_original_exception():+ """If the fallback attempt itself fails with a MidStreamFallbackError+ wrapping a real provider exception, the client must see that real+ exception, not the internal MidStreamFallbackError."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_overloaded_error_chunk()])+ original_exception = litellm.APIError(+ status_code=503,+ message="fallback also overloaded",+ llm_provider="bedrock",+ model="fallback",+ )+ fallback_failure = MidStreamFallbackError(+ message="fallback failed",+ model="fallback",+ llm_provider="bedrock",+ original_exception=original_exception,+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(side_effect=fallback_failure),+ ):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ with pytest.raises(litellm.APIError) as exc_info:+ async for _ in wrapped:+ pass++ assert exc_info.value is original_exception+++ # -------- _dispatch_generic_call_type --------+++ @pytest.mark.asyncio+ async def test_dispatch_generic_call_type_routes_anthropic_messages_through_streaming_fallbacks():+ router = _anthropic_messages_make_router()++ async def fake_original(**_kwargs):+ return {"id": "msg_1"}++ with patch.object(+ router,+ "_aanthropic_messages_with_streaming_fallbacks",+ new=AsyncMock(return_value="anthropic-result"),+ ) as mock_anthropic:+ out = await router._dispatch_generic_call_type(+ call_type="anthropic_messages",+ original_function=fake_original,+ model="primary",+ )+ assert out == "anthropic-result"+ mock_anthropic.assert_awaited_once()+++ @pytest.mark.asyncio+ async def test_dispatch_generic_call_type_other_call_types_use_generic_fallback():+ router = _anthropic_messages_make_router()++ async def fake_original(**_kwargs):+ return {"id": "file_1"}++ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(return_value="generic-result"),+ ) as mock_generic:+ out = await router._dispatch_generic_call_type(+ call_type="afile_delete",+ original_function=fake_original,+ model="primary",+ )+ assert out == "generic-result"+ mock_generic.assert_awaited_once()+++ @pytest.mark.asyncio+ async def test_factory_function_anthropic_messages_uses_streaming_fallback_dispatch():+ """anthropic_messages must be wired through the mid-stream-fallback-aware+ path rather than the bare generic dispatch every other call type without+ special handling uses."""+ router = _anthropic_messages_make_router()+ wrapped = router.factory_function(litellm.anthropic_messages, call_type="anthropic_messages")+ assert callable(wrapped)++ with patch.object(+ router,+ "_aanthropic_messages_with_streaming_fallbacks",+ new=AsyncMock(return_value="ok"),+ ) as mock_anthropic:+ result = await wrapped(model="primary")+ assert result == "ok"+ mock_anthropic.assert_awaited_once()+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_zero_attempted_fallbacks():+ """A request served by the primary model group records attempted_fallbacks=0 and+ the requested model group in metadata, mirroring the x-litellm-attempted-fallbacks header."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_route_bucket_not_litellm_metadata():+ """A chat completion carrying both metadata buckets gets stamped in the route's bucket+ (metadata), matching where run_async_fallback rewrites, so the two never diverge."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {}+ litellm_metadata = {"client_key": "client_value"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ litellm_metadata=litellm_metadata,+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+ assert litellm_metadata["client_key"] == "client_value"+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_overrides_client_supplied_stamp_values():+ """Client-supplied attempted_fallbacks and original_model_group are replaced on entry,+ so a reused metadata dict or a spoofed value cannot leak stale attribution into logs."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {"attempted_fallbacks": 99, "original_model_group": "stale-group"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_despite_forged_reentry_params():+ """A client injecting fallback_depth or a JSON-shaped attempted_targets via request+ litellm params cannot skip the entry stamp; only the router's own in-process+ AttemptedFallbackTargets instance marks a genuine re-entrant hop."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {"attempted_fallbacks": 99, "original_model_group": "spoofed-group"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ fallback_depth=3,+ attempted_targets={"keys": ["spoofed-group"]},+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_skips_stamp_on_genuine_reentrant_hop():+ """A re-entrant hop carrying the router's own AttemptedFallbackTargets instance keeps+ the per-hop metadata that run_async_fallback wrote instead of resetting it to zero."""+ from litellm.router_utils.fallback_event_handlers import AttemptedFallbackTargets++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {"attempted_fallbacks": 1, "original_model_group": "prod-chat"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ attempted_targets=AttemptedFallbackTargets(keys=frozenset(("prod-chat",))),+ )++ assert metadata["attempted_fallbacks"] == 1+ assert metadata["original_model_group"] == "prod-chat"+++ def _record_router_acompletion_kwargs(router: litellm.Router) -> list:+ """Spy on router._acompletion, recording each call's kwargs while delegating through."""+ records = []+ original_acompletion = router._acompletion++ @functools.wraps(original_acompletion)+ async def _spy(*args, **spy_kwargs):+ records.append(spy_kwargs)+ return await original_acompletion(*args, **spy_kwargs)++ router._acompletion = _spy+ return records+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_scrubs_spoofed_values_from_sibling_bucket():+ """Spend logs read a truthy litellm_metadata dict in preference to metadata, so spoofed+ stamp keys planted in the bucket the route does not own are removed on entry, in place,+ before they can flow into the spend log row."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {}+ litellm_metadata = {+ "attempted_fallbacks": 99,+ "original_model_group": "spoofed-group",+ "client_key": "client_value",+ }+ downstream_calls = _record_router_acompletion_kwargs(router)++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ litellm_metadata=litellm_metadata,+ )++ assert len(downstream_calls) == 1+ downstream_sibling = downstream_calls[0]["litellm_metadata"]+ assert "attempted_fallbacks" not in downstream_sibling+ assert "original_model_group" not in downstream_sibling+ assert downstream_sibling["client_key"] == "client_value"+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+ assert litellm_metadata["client_key"] == "client_value"+ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_scrubs_sibling_bucket_in_place():+ """Everything below the router resolves the bucket by key presence, so the scrub edits+ the caller's dict object like every other router bucket write. Rebinding kwargs to a+ scrubbed copy detaches the proxy's request_data write-backs (guardrail telemetry, retry+ accounting) from the object the spend row is built from."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ litellm_metadata = {+ "attempted_fallbacks": 7,+ "original_model_group": "planted-group",+ "client_key": "client_value",+ }+ caller_snapshot = copy.deepcopy(litellm_metadata)+ downstream_calls = _record_router_acompletion_kwargs(router)++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata={},+ litellm_metadata=litellm_metadata,+ )++ assert len(downstream_calls) == 1+ assert downstream_calls[0]["litellm_metadata"] is litellm_metadata+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+ assert litellm_metadata["client_key"] == caller_snapshot["client_key"]+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_aliased_buckets_on_every_call():+ """One dict object passed as both metadata and litellm_metadata: the first call's own+ stamp puts the reserved keys into the shared object, so the second call enters the+ scrub with them present. Scrubbing in place keeps the stamp and the bucket on the same+ object; a scrubbed copy would leave the spend reader's preferred bucket unstamped."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "chat-group",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ shared_metadata = {"team": "alpha"}+ downstream_calls = _record_router_acompletion_kwargs(router)++ for _ in range(3):+ await router.acompletion(+ model="chat-group",+ messages=[{"role": "user", "content": "hey"}],+ metadata=shared_metadata,+ litellm_metadata=shared_metadata,+ )++ assert len(downstream_calls) == 3+ for call_kwargs in downstream_calls:+ assert call_kwargs["litellm_metadata"] is shared_metadata+ assert call_kwargs["metadata"] is shared_metadata+ assert call_kwargs["litellm_metadata"]["attempted_fallbacks"] == 0+ assert call_kwargs["litellm_metadata"]["original_model_group"] == "chat-group"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_passes_clean_sibling_bucket_through_unchanged():+ """A sibling bucket carrying no reserved stamp keys is forwarded downstream as the+ caller's own object with no copy made, matching pre-scrub behavior. Retry accounting+ stamped into that bucket downstream predates the scrub and is out of its scope."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ litellm_metadata = {"client_key": "client_value"}+ downstream_calls = _record_router_acompletion_kwargs(router)++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata={},+ litellm_metadata=litellm_metadata,+ )++ assert len(downstream_calls) == 1+ assert downstream_calls[0]["litellm_metadata"] is litellm_metadata+ assert litellm_metadata["client_key"] == "client_value"+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+++ @pytest.mark.asyncio+ async def test_run_async_fallback_keeps_caller_metadata_keys_on_the_wire(monkeypatch):+ """Under enable_preview_features, add_openai_metadata forwards only the first 16+ string pairs of request metadata to the provider body, so the fallback hop must+ spread caller keys before the router's own stamps: a stamp inserted first evicts+ the caller's 16th key from the wire while the internal stamp rides in its place."""+ monkeypatch.setattr(litellm, "enable_preview_features", True)+ caller_metadata = {f"user_key_{i}": f"value_{i}" for i in range(16)}+ router = litellm.Router(+ model_list=[+ {+ "model_name": "primary-group",+ "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "sk-test"},+ },+ {+ "model_name": "fallback-group",+ "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "sk-test"},+ },+ ],+ fallbacks=[{"primary-group": ["fallback-group"]}],+ num_retries=0,+ )++ wire_bodies = []++ def _respond(request: httpx.Request) -> httpx.Response:+ wire_bodies.append(json.loads(request.content))+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-wire",+ "object": "chat.completion",+ "created": 1,+ "model": "gpt-3.5-turbo",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ },+ )++ client = openai.AsyncOpenAI(+ api_key="sk-test",+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(_respond)),+ )++ await router.acompletion(+ model="primary-group",+ messages=[{"role": "user", "content": "hey"}],+ metadata=dict(caller_metadata),+ mock_testing_fallbacks=True,+ client=client,+ )++ assert len(wire_bodies) == 1+ assert wire_bodies[0]["metadata"] == caller_metadata++ wire_bodies.clear()+ small_metadata = {"team": "alpha", "env": "prod"}+ await router.acompletion(+ model="primary-group",+ messages=[{"role": "user", "content": "hey again"}],+ metadata=dict(small_metadata),+ mock_testing_fallbacks=True,+ client=client,+ )++ assert len(wire_bodies) == 1+ small_wire = wire_bodies[0]["metadata"]+ assert {k: small_wire[k] for k in small_metadata} == small_metadata+ assert small_wire["original_model_group"] == "primary-group"+ assert small_wire["model_group"] == "fallback-group"+++ @pytest.mark.asyncio+ async def test_run_async_fallback_two_hop_chain_reports_entry_group_and_hop_count():+ """A two-hop fallback chain stamps attempted_fallbacks=2 on the final leg and keeps+ original_model_group at the group requested on entry: a later hop's stamp appends+ after caller keys without overriding the value stamped by an earlier hop."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "group-a",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "litellm.InternalServerError"},+ },+ {+ "model_name": "group-b",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "litellm.InternalServerError"},+ },+ {+ "model_name": "group-c",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "ok"},+ },+ ],+ fallbacks=[{"group-a": ["group-b"]}, {"group-b": ["group-c"]}],+ num_retries=0,+ )+ metadata = {}+ leg_records = []+ original_acompletion = router._acompletion++ @functools.wraps(original_acompletion)+ async def _spy(*args, **spy_kwargs):+ leg_records.append((spy_kwargs.get("model"), copy.deepcopy(spy_kwargs.get("metadata"))))+ return await original_acompletion(*args, **spy_kwargs)++ router._acompletion = _spy++ await router.acompletion(+ model="group-a",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ )++ assert [model for model, _ in leg_records] == ["group-a", "group-b", "group-c"]+ hop_one_metadata = leg_records[1][1]+ assert hop_one_metadata["attempted_fallbacks"] == 1+ assert hop_one_metadata["original_model_group"] == "group-a"+ assert hop_one_metadata["model_group"] == "group-b"+ hop_two_metadata = leg_records[2][1]+ assert hop_two_metadata["attempted_fallbacks"] == 2+ assert hop_two_metadata["original_model_group"] == "group-a"+ assert hop_two_metadata["model_group"] == "group-c"+ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "group-a"+++ def _permission_denied_error() -> litellm.PermissionDeniedError:+ return litellm.PermissionDeniedError(+ message="OpenrouterException - this key has no access to the model",+ llm_provider="openrouter",+ model="openrouter/openai/gpt-4o",+ response=httpx.Response(status_code=403, request=httpx.Request(method="POST", url="https://openrouter.ai")),+ )+++ def test_permission_denied_error_is_not_retried_against_a_single_deployment():+ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openrouter/openai/gpt-4o", "api_key": "sk-test"}},+ ]+ )++ with pytest.raises(litellm.PermissionDeniedError):+ router.should_retry_this_error(+ error=_permission_denied_error(),+ healthy_deployments=router.model_list,+ all_deployments=router.model_list,+ )+++ def test_permission_denied_error_is_retried_when_other_deployments_exist():+ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openrouter/openai/gpt-4o", "api_key": "sk-test"}},+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-test"}},+ ]+ )++ assert (+ router.should_retry_this_error(+ error=_permission_denied_error(),+ healthy_deployments=router.model_list,+ all_deployments=router.model_list,+ )+ is True+ )+++ class _AllowlistFallbackAccessCheck:+ def __init__(self, allowed_models: frozenset[str]):+ self.allowed_models = allowed_models+ self.checked_models = []++ async def __call__(self, *, model, request_kwargs, llm_router):+ self.checked_models.append(model)+ return model in self.allowed_models+++ def _router_with_failing_primary(fallback_access_check) -> Router:+ return Router(+ model_list=[+ {+ "model_name": "primary",+ "litellm_params": {+ "model": "openai/primary",+ "api_key": "k",+ "mock_response": Exception("primary is down"),+ },+ },+ {+ "model_name": "secret-fallback",+ "litellm_params": {+ "model": "openai/secret",+ "api_key": "k",+ "mock_response": "served by secret-fallback",+ },+ },+ ],+ fallbacks=[{"primary": ["secret-fallback"]}],+ num_retries=0,+ fallback_access_check=fallback_access_check,+ )+++ @pytest.mark.asyncio+ async def test_fallback_access_check_blocks_config_fallback_the_caller_cannot_use():+ access_check = _AllowlistFallbackAccessCheck(allowed_models=frozenset())+ router = _router_with_failing_primary(access_check)++ with pytest.raises(Exception, match="primary is down"):+ await router.acompletion(model="primary", messages=[{"role": "user", "content": "hi"}])++ assert access_check.checked_models == ["secret-fallback"]+++ @pytest.mark.asyncio+ async def test_fallback_access_check_lets_an_authorized_config_fallback_through():+ router = _router_with_failing_primary(_AllowlistFallbackAccessCheck(allowed_models=frozenset({"secret-fallback"})))++ response = await router.acompletion(model="primary", messages=[{"role": "user", "content": "hi"}])++ assert response.choices[0].message.content == "served by secret-fallback"+++ @pytest.mark.asyncio+ async def test_router_without_fallback_access_check_attempts_every_config_fallback():+ router = _router_with_failing_primary(None)++ response = await router.acompletion(model="primary", messages=[{"role": "user", "content": "hi"}])++ assert response.choices[0].message.content == "served by secret-fallback"+++ def _resolution_router() -> Router:+ return Router(+ model_list=[+ {"model_name": "pinned", "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-test"}},+ {"model_name": "pooled", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "sk-test"}},+ {"model_name": "pooled", "litellm_params": {"model": "anthropic/claude-haiku-4-5", "api_key": "sk-test"}},+ {"model_name": "bedrock/*", "litellm_params": {"model": "bedrock/*", "api_key": "sk-test"}},+ ],+ model_group_alias={"nickname": "pinned"},+ )+++ @pytest.mark.parametrize(+ "model_name,expected",+ [+ ("pinned", ("openai/gpt-4o",)),+ ("nickname", ("openai/gpt-4o",)),+ ("pooled", ("openai/gpt-4o-mini", "anthropic/claude-haiku-4-5")),+ ("bedrock/anthropic.claude-3-5-sonnet", ("bedrock/anthropic.claude-3-5-sonnet",)),+ ("never-configured", ()),+ ],+ ids=["exact-name", "model-group-alias", "every-member-of-a-pool", "wildcard-expands", "resolves-to-nothing"],+ )+ def test_resolved_litellm_models_answers_through_every_channel_a_request_uses(+ model_name: str, expected: tuple[str, ...]+ ) -> None:+ """A caller comparing two names by what serves them needs each channel the request path+ composes, since the deployment name an admin picked carries no information on its own.++ `resolves-to-nothing` is the contract that keeps the fallback out of here: an empty+ result is not "the call fails", so what to do about it stays each caller's policy.+ """+ assert set(_resolution_router().resolved_litellm_models(model_name)) == set(expected)+++ class TestTierParamsTheTargetAccepts:+ """A tier's litellm_params are applied to every request that tier routes, so one the target+ cannot take raised UnsupportedParamsError before the request left the proxy, turning the whole+ tier into a 400."""++ @pytest.fixture(autouse=True)+ def force_local_model_cost(self, monkeypatch):+ from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap++ monkeypatch.setattr(litellm, "model_cost", GetModelCostMap.load_local_model_cost_map())++ @staticmethod+ def _router(model: str) -> litellm.Router:+ return litellm.Router(+ model_list=[{"model_name": "tiered", "litellm_params": {"model": model, "api_key": "sk-x"}}]+ )++ def test_drops_a_param_no_deployment_declares(self):+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})++ assert accepted == {}++ def test_keeps_a_param_the_deployment_declares(self):+ router = self._router("fireworks_ai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})++ assert accepted == {"reasoning_effort": "max"}++ @pytest.mark.parametrize(+ "control, value",+ [+ ("api_base", "https://example.invalid"),+ ("api_key", "sk-tier"),+ ("base_url", "https://example.invalid"),+ ("timeout", 30),+ ("default_headers", {"x-tier": "1"}),+ ("organization", "org-tier"),+ ("deployment_id", "dep-tier"),+ ],+ )+ def test_keeps_credentials_and_transport_controls(self, control, value):+ """These are not chat completion params, so get_optional_params never compares them against+ a provider's supported list. Filtering on "is this an OpenAI param" would discard the+ configuration the request needs while never touching what the provider would reject."""+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})++ assert accepted == {control: value}++ @pytest.mark.parametrize(+ "control, value",+ [+ ("additional_drop_params", ["seed"]),+ ("drop_params", True),+ ("allowed_openai_params", ["seed"]),+ ("api_version", "2024-02-01"),+ ("metadata", {"tier": "complex"}),+ ],+ )+ def test_keeps_litellm_controls_the_provider_never_lists(self, control, value):+ """No provider lists a litellm control among its supported params, so "no deployment+ declares it" means litellm consumes it, not that the target refuses it. Dropping+ drop_params or additional_drop_params would silently disable the operator's sanitization."""+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})++ assert accepted == {control: value}++ def test_tier_allowlist_protects_the_param_it_names(self):+ """allowed_openai_params is the documented escape hatch for an incomplete supported-params+ list, and request-time validation extends the supported list with it, so a param the tier+ both sets and allowlists would never 400 and must not be dropped."""+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}, {}+ )++ assert accepted == {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}++ def test_request_allowlist_protects_the_param_it_names(self):+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"reasoning_effort": "max"}, {"allowed_openai_params": ["reasoning_effort"]}+ )++ assert accepted == {"reasoning_effort": "max"}++ def test_allowlist_protects_only_the_params_it_names(self):+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["seed"]}, {}+ )++ assert accepted == {"allowed_openai_params": ["seed"]}++ def test_declared_param_allowlist_ignores_malformed_declarations(self):+ """A str is iterable, so without the type guard a YAML scalar mistake like+ allowed_openai_params: reasoning_effort would allowlist single characters."""+ assert litellm.Router._declared_param_allowlist({"allowed_openai_params": ["reasoning_effort", 3]}) == frozenset(+ {"reasoning_effort"}+ )+ assert litellm.Router._declared_param_allowlist({"allowed_openai_params": "reasoning_effort"}) == frozenset()+ assert litellm.Router._declared_param_allowlist({}) == frozenset()++ def test_deployment_accepts_param_honors_deployment_allowlist(self):+ deployment = {+ "model_name": "x",+ "litellm_params": {"model": "novita/moonshotai/kimi-k3", "allowed_openai_params": ["reasoning_effort"]},+ }++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True++ def test_keeps_a_token_ceiling_the_provider_spells_differently(self):+ """petals lists max_tokens but not max_completion_tokens. A tier ceiling in the unsupported+ spelling is a cost bound: dropping it would let a caller's larger max_tokens through where+ today the mismatch fails loudly."""+ router = self._router("petals/petals-team/StableBeluga2")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"max_completion_tokens": 100, "reasoning_effort": "max"}, {}+ )++ assert accepted == {"max_completion_tokens": 100}++ def test_keeps_extra_headers_even_when_the_provider_omits_it(self):+ """Several providers leave extra_headers out of their supported params, so the filter would+ drop it. Headers carry auth and tenancy, so sending fewer than the operator configured is+ worse than the error they already get."""+ router = self._router("ai21/jamba-1.5-mini")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"extra_headers": {"x-tenant": "acme"}, "reasoning_effort": "max"}, {}+ )++ assert accepted == {"extra_headers": {"x-tenant": "acme"}}++ def test_keeps_a_param_any_deployment_in_the_group_declares(self):+ """Routing has not picked a deployment yet, so one capable member keeps the param alive."""+ router = litellm.Router(+ model_list=[+ {"model_name": "tiered", "litellm_params": {"model": "novita/moonshotai/kimi-k3", "api_key": "k"}},+ {"model_name": "tiered", "litellm_params": {"model": "fireworks_ai/kimi-k3", "api_key": "k"}},+ ]+ )++ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})++ assert accepted == {"reasoning_effort": "max"}++ def test_deployment_accepts_param_honors_base_model(self):+ """An azure deployment named after the deployment rather than the model carries the real+ model in base_model, and request-time mapping resolves capability through it, so the filter+ has to ask the same question or it drops a param the deployment accepts."""+ by_model_info = {+ "model_name": "x",+ "litellm_params": {"model": "azure/my-gpt5-deploy"},+ "model_info": {"base_model": "azure/gpt-5"},+ }+ by_litellm_params = {+ "model_name": "x",+ "litellm_params": {"model": "azure/my-gpt5-deploy", "base_model": "azure/gpt-5"},+ }+ without_hint = {"model_name": "x", "litellm_params": {"model": "azure/my-gpt5-deploy"}}++ assert litellm.Router._deployment_accepts_param(by_model_info, "x", "reasoning_effort") is True+ assert litellm.Router._deployment_accepts_param(by_litellm_params, "x", "reasoning_effort") is True+ assert litellm.Router._deployment_accepts_param(without_hint, "x", "reasoning_effort") is False++ def test_deployment_accepts_param_reads_the_provider(self):+ deployment = {"model_name": "x", "litellm_params": {"model": "fireworks_ai/kimi-k3"}}++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True++ def test_deployment_accepts_param_is_false_when_the_provider_omits_it(self):+ deployment = {"model_name": "x", "litellm_params": {"model": "novita/moonshotai/kimi-k3"}}++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is False++ @pytest.mark.parametrize(+ "deployment",+ [{"model_name": "x"}, {"model_name": "x", "litellm_params": {}}, {"model_name": "x", "litellm_params": {"model": "not-a-real-provider/nope"}}],+ )+ def test_deployment_accepts_param_fails_open(self, deployment):+ """An unresolvable deployment must not be the reason a param is dropped."""+ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True++ @pytest.mark.parametrize(+ "litellm_params",+ [+ {"model": "github_copilot/gpt-4o"},+ {"model": "chatgpt/gpt-5"},+ {"model": "gpt-4o", "custom_llm_provider": "github_copilot"},+ ],+ )+ def test_deployment_accepts_param_never_asks_a_provider_whose_lookup_authenticates(+ self, litellm_params, monkeypatch+ ):+ """Resolving github_copilot or chatgpt runs their OAuth device flow, so a capability+ question asked from the routing path can freeze the event loop for minutes waiting on a+ human. The deployment counts as accepting everything, and the lookup is never made: an+ exception-based sentinel cannot prove that, because the filter swallows exceptions into+ the same keep answer."""+ lookups: list = []++ def _record(*args, **kwargs):+ lookups.append((args, kwargs))+ raise RuntimeError("provider resolution must not run for an authenticating provider")++ monkeypatch.setattr(litellm, "get_llm_provider", _record)+ deployment = {"model_name": "x", "litellm_params": litellm_params}++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True+ assert lookups == []++ def test_keeps_everything_for_an_unknown_group(self):+ """An unresolvable target must never narrow what the request already did."""+ router = self._router("fireworks_ai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("no-such-group", {"reasoning_effort": "max"}, {})++ assert accepted == {"reasoning_effort": "max"}diff --cc tests/test_litellm/vector_stores/test_main.pyindex 3fdf4d9daa5,00000000000..d01e696906amode 100644,000000..100644--- a/tests/test_litellm/vector_stores/test_main.py+++ b/tests/test_litellm/vector_stores/test_main.py@@@ -1,77 -1,0 +1,78 @@@+"""+Tests for litellm/vector_stores/main.py.++Pins the router threading contract for vector store search: the router is an+explicit named parameter that reaches the HTTP handler, and it must never leak+into litellm_params/kwargs where logging would model_dump() it (the #19550+serialization trap).+"""++from unittest.mock import MagicMock, patch++import litellm.vector_stores.main as vector_stores_main+from litellm.vector_stores.main import search++MOCK_SEARCH_RESPONSE = {+ "object": "vector_store.search_results.page",+ "search_query": "q",+ "data": [],+}+++def test_search_threads_router_to_handler():+ """search() must pass its router param through to the HTTP handler"""+ mock_router = MagicMock()+ logger = MagicMock()++ with (- patch(++ patch( # test-quality-ok: stubs provider config resolution; the seam under test is the router kwarg threading+ "litellm.vector_stores.main.ProviderConfigManager.get_provider_vector_stores_config",+ return_value=MagicMock(),+ ),- patch.object(++ patch.object( # test-quality-ok: the handler call is the observable boundary for the router kwarg contract+ vector_stores_main.base_llm_http_handler,+ "vector_store_search_handler",+ return_value=MOCK_SEARCH_RESPONSE,+ ) as mock_handler,+ ):- search(++ response = search(+ vector_store_id="bkt:idx",+ query="q",+ custom_llm_provider="s3_vectors",+ router=mock_router,+ litellm_logging_obj=logger,+ )+++ assert response == MOCK_SEARCH_RESPONSE+ mock_handler.assert_called_once()+ assert mock_handler.call_args.kwargs["router"] is mock_router+++def test_search_router_not_in_litellm_params():+ """Regression (#19550 class): the router must stay out of GenericLiteLLMParams,+ otherwise pre-call logging model_dump()s it and breaks serialization."""+ mock_router = MagicMock()+ logger = MagicMock()++ with (- patch(++ patch( # test-quality-ok: stubs provider config resolution; the seam under test is litellm_params contents+ "litellm.vector_stores.main.ProviderConfigManager.get_provider_vector_stores_config",+ return_value=MagicMock(),+ ),- patch.object(++ patch.object( # test-quality-ok: the handler call is where a leaked router in litellm_params would surface+ vector_stores_main.base_llm_http_handler,+ "vector_store_search_handler",+ return_value=MOCK_SEARCH_RESPONSE,+ ) as mock_handler,+ ):+ search(+ vector_store_id="bkt:idx",+ query="q",+ custom_llm_provider="s3_vectors",+ router=mock_router,+ litellm_logging_obj=logger,+ )++ litellm_params = mock_handler.call_args.kwargs["litellm_params"]+ assert "router" not in litellm_params.model_dump(exclude_none=True)+ assert getattr(litellm_params, "router", None) is Nonediff --cc ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/VectorStoreTester.tsxindex 65b31bb911a,6d12880319b..a9c4e0d1061--- a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/VectorStoreTester.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/VectorStoreTester.tsx@@@ -69,9 -66,7 +68,9 @@@ export const VectorStoreTester: React.FsetQuery("");} catch (error) {console.error("Error searching vector store:", error);- toast.fromError("Failed to search vector store");+ const errorMessage = error instanceof Error ? error.message : String(error);- NotificationsManager.fromBackend(errorMessage);++ toast.fromError(errorMessage);+ setSearchHistory((prev) => [{ query, response: null, error: errorMessage, timestamp: Date.now() }, ...prev]);} finally {setIsLoading(false);}@@@ -232,10 -227,8 +231,14 @@@);})}</div>- ) : entry.error ? (- <div className="text-sm text-destructive break-words">Search failed: {entry.error}</div>) : (-- <div className="text-sm text-muted-foreground">No results found</div>++ <div++ className={++ entry.error ? "text-sm break-words text-destructive" : "text-sm text-muted-foreground"++ }++ >++ {entry.error ? `Search failed: ${entry.error}` : "No results found"}++ </div>)}</div></div>