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 remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_vector_store_request_embedding_resolution
mateo-berri61ae06d4d9ab
diff --cc litellm/llms/azure_ai/vector_stores/transformation.pyindex 044b8f5243c,64e72b819b1..db1a0fc89a3--- a/litellm/llms/azure_ai/vector_stores/transformation.py+++ b/litellm/llms/azure_ai/vector_stores/transformation.py@@@ -1,4 -1,3 +1,6 @@@++from __future__ import annotations+++from collections.abc import Mapping, Sequencefrom typing import TYPE_CHECKING, Any, Finalimport httpx@@@ -116,64 -114,67 +119,66 @@@ class AzureAIVectorStoreConfig(BaseQuervector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,api_base: str,litellm_logging_obj: LiteLLMLoggingObj,- litellm_params: dict,- extra_body: dict[str, Any] | None = None,- router: "Router | None" = None,- ) -> tuple[str, dict[str, Any]]:- """- Transform search request for Azure AI Search API-- Generates embeddings using litellm.embeddings and constructs Azure AI Search request- """- # Convert query to string if it's a list- if isinstance(query, list):- query = " ".join(query)-- # Get embedding model from litellm_params (required)- embedding_model: Final = litellm_params.get("litellm_embedding_model")- if not embedding_model:- raise ValueError(- "embedding_model is required in litellm_params for Azure AI Search. "- "Example: litellm_params['embedding_model'] = 'azure/text-embedding-3-large'"- )-- embedding_config: Final = litellm_params.get("litellm_embedding_config", {})- if not embedding_config:- raise ValueError(- "embedding_config is required in litellm_params for Azure AI Search. "- "Example: litellm_params['embedding_config'] = {'api_base': 'https://krris-mh44uf7y-eastus2.cognitiveservices.azure.com/', 'api_key': 'os.environ/AZURE_API_KEY', 'api_version': '2025-09-01'}"- )-- # Get vector field name (defaults to contentVector)+ litellm_params: Mapping[str, object],+ extra_body: Mapping[str, object] | None = None,++ router: Router | None = None,+ embedding_executor: VectorStoreEmbeddingExecutor | None = None,+ ) -> tuple[str, dict[str, object]]:+ query_text: Final = self.query_text(query)- query_vector: Final = self.embed_query(query_text, litellm_params, embedding_executor)++ query_vector: Final = self.embed_query(query_text, litellm_params, embedding_executor, router)+ return self._search_request(+ vector_store_id,+ query_text,+ query_vector,+ vector_store_search_optional_params,+ api_base,+ litellm_logging_obj,+ litellm_params,+ )++ async def atransform_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,+ embedding_executor: VectorStoreEmbeddingExecutor | None = None,+ ) -> tuple[str, dict[str, object]]:+ query_text: Final = self.query_text(query)- query_vector: Final = await self.aembed_query(query_text, litellm_params, embedding_executor)++ query_vector: Final = await self.aembed_query(query_text, litellm_params, embedding_executor, router)+ return self._search_request(+ vector_store_id,+ query_text,+ query_vector,+ vector_store_search_optional_params,+ api_base,+ litellm_logging_obj,+ litellm_params,+ )++ @staticmethod+ def _search_request(+ vector_store_id: str,+ query_text: str,+ query_vector: Sequence[float],+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,+ api_base: str,+ litellm_logging_obj: LiteLLMLoggingObj,+ litellm_params: Mapping[str, object],+ ) -> tuple[str, dict[str, object]]:vector_field: Final = litellm_params.get("azure_search_vector_field", "contentVector")-- # Get top_k (number of results to return)top_k: Final = vector_store_search_optional_params.get("top_k", 10)-- # Generate embedding for the query using litellm.embeddings- try:- embedding_response: Final = litellm.embedding(- model=embedding_model,- input=[query],- **embedding_config,- )- query_vector: Final = embedding_response.data[0]["embedding"]- except Exception as e:- raise Exception(f"Failed to generate embedding for query: {e}")-- # Azure AI Search endpoint for search- index_name: Final = vector_store_id # vector_store_id is the index name- url: Final = f"{api_base}/indexes/{index_name}/docs/search?api-version=2024-07-01"-- # Build the request body for Azure AI Search with vector search- request_body: Final = {- "search": "*", # Get all documents (filtered by vector similarity)- "vectorQueries": [- {- "vector": query_vector,- "fields": vector_field,- "kind": "vector",- "k": top_k, # Number of nearest neighbors to return- }- ],- "select": "id,content", # Fields to return (customize based on schema)+ litellm_logging_obj.model_call_details["input"] = query_text+ litellm_logging_obj.model_call_details["embedding_model"] = litellm_params.get("litellm_embedding_model")+ litellm_logging_obj.model_call_details["top_k"] = top_k+ return f"{api_base}/indexes/{vector_store_id}/docs/search?api-version=2024-07-01", {+ "search": "*",+ "vectorQueries": [{"vector": query_vector, "fields": vector_field, "kind": "vector", "k": top_k}],+ "select": "id,content","top": top_k,}diff --cc litellm/llms/base_llm/vector_store/transformation.pyindex 95863266bf7,63e99c0915a..e7c549b7358--- a/litellm/llms/base_llm/vector_store/transformation.py+++ b/litellm/llms/base_llm/vector_store/transformation.py@@@ -137,6 -58,7 +137,7 @@@ class BaseVectorStoreConfiglitellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,extra_body: dict[str, Any] | None = None,- router: "Router | None" = None,++ router: Router | None = None,) -> tuple[str, dict]:pass@@@ -149,6 -71,7 +150,7 @@@litellm_logging_obj: LiteLLMLoggingObj,litellm_params: dict,extra_body: dict[str, Any] | None = None,- router: "Router | None" = None,++ router: Router | None = None,) -> tuple[str, dict]:"""Optional async version of transform_search_vector_store_request.@@@ -237,103 -161,6 +240,115 @@@return 0.0, 0.0+_EMPTY_EMBEDDING_CONFIGURATION: Final[Mapping[str, object]] = MappingProxyType({})+_QUERY_VECTOR: Final = TypeAdapter(list[float])+++class BaseQueryEmbeddingVectorStoreConfig(BaseVectorStoreConfig):+ @abstractmethod+ 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,+ embedding_executor: VectorStoreEmbeddingExecutor | None = None,+ ) -> tuple[str, dict[str, object]]:+ pass++ async def atransform_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,+ embedding_executor: VectorStoreEmbeddingExecutor | None = None,+ ) -> tuple[str, dict[str, object]]:+ return self.transform_search_vector_store_request(+ vector_store_id=vector_store_id,+ query=query,+ vector_store_search_optional_params=vector_store_search_optional_params,+ api_base=api_base,+ litellm_logging_obj=litellm_logging_obj,+ litellm_params=litellm_params,+ extra_body=extra_body,++ router=router,+ embedding_executor=embedding_executor,+ )++ @staticmethod+ def query_text(query: str | Sequence[str]) -> str:+ return query if isinstance(query, str) else " ".join(query)++ @staticmethod+ def query_embedding_model(litellm_params: Mapping[str, object]) -> str:+ embedding_model: Final = litellm_params.get("litellm_embedding_model")+ if isinstance(embedding_model, str) and embedding_model:+ return embedding_model+ raise ValueError(+ "litellm_embedding_model is required in litellm_params for this vector store. "+ "Example: litellm_params['litellm_embedding_model'] = 'openai/text-embedding-3-small'"+ )++ @staticmethod+ def query_embedding_configuration(litellm_params: Mapping[str, object]) -> Mapping[str, object]:+ configuration: Final = litellm_params.get("litellm_embedding_config")+ if isinstance(configuration, Mapping):+ return {str(key): value for key, value in configuration.items()} # pyright: ignore[reportUnknownVariableType, reportUnknownArgumentType] # litellm_params is an untyped dict, keys are re-validated as str here+ return _EMPTY_EMBEDDING_CONFIGURATION+++ @staticmethod++ def query_embedding_executor(++ embedding_executor: VectorStoreEmbeddingExecutor | None,++ router: Router | None,++ ) -> VectorStoreEmbeddingExecutor:++ if embedding_executor is not None:++ return embedding_executor++ if router is not None:++ return RouterVectorStoreEmbeddingExecutor(router=router, metadata=MappingProxyType({}))++ return LiteLLMVectorStoreEmbeddingExecutor()+++ def embed_query(+ self,+ query_text: str,+ litellm_params: Mapping[str, object],+ embedding_executor: VectorStoreEmbeddingExecutor | None,++ router: Router | None = None,+ ) -> Sequence[float]:+ model: Final = self.query_embedding_model(litellm_params)+ configuration: Final = self.query_embedding_configuration(litellm_params)- executor: Final = (- embedding_executor if embedding_executor is not None else LiteLLMVectorStoreEmbeddingExecutor()- )++ executor: Final = self.query_embedding_executor(embedding_executor, router)+ try:+ response: Final = executor.embed(model, query_text, configuration)+ except Exception as e:+ raise Exception(f"Failed to generate embedding for query: {e}")+ return _QUERY_VECTOR.validate_python(response.data[0]["embedding"]) # pyright: ignore[reportUnknownMemberType] # EmbeddingResponse.data is an untyped list, the vector is validated here++ async def aembed_query(+ self,+ query_text: str,+ litellm_params: Mapping[str, object],+ embedding_executor: VectorStoreEmbeddingExecutor | None,++ router: Router | None = None,+ ) -> Sequence[float]:+ model: Final = self.query_embedding_model(litellm_params)+ configuration: Final = self.query_embedding_configuration(litellm_params)- executor: Final = (- embedding_executor if embedding_executor is not None else LiteLLMVectorStoreEmbeddingExecutor()- )++ executor: Final = self.query_embedding_executor(embedding_executor, router)+ try:+ response: Final = await executor.aembed(model, query_text, configuration)+ except Exception as e:+ raise Exception(f"Failed to generate embedding for query: {e}")+ return _QUERY_VECTOR.validate_python(response.data[0]["embedding"]) # pyright: ignore[reportUnknownMemberType] # EmbeddingResponse.data is an untyped list, the vector is validated here++class BaseDirectVectorStoreConfig(BaseVectorStoreConfig):"""Base config for vector store providers whose datastore has no HTTP API@@@ -376,6 -201,7 +391,7 @@@litellm_logging_obj: LiteLLMLoggingObj,litellm_params: Mapping[str, object],extra_body: Mapping[str, object] | None = None,- router: "Router | None" = None,++ router: Router | None = None,) -> NoReturn:raise NotImplementedError("Direct vector store providers execute the search themselves; no HTTP request shape")diff --cc litellm/llms/custom_httpx/llm_http_handler.pyindex c0ef7456680,6f42d42de00..fb4d2b3d671--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@@ -9741,7 -9740,7 +9743,8 @@@ class BaseLLMHTTPHandlerlitellm_logging_obj=logging_obj,litellm_params=dict(litellm_params),extra_body=extra_body,+ router=router,+ embedding_executor=embedding_executor,)else:(@@@ -9858,33 -9857,19 +9864,35 @@@litellm_params=dict(litellm_params),)- (- url,- request_body,- ) = vector_store_provider_config.transform_search_vector_store_request(- vector_store_id=vector_store_id,- query=query,- vector_store_search_optional_params=vector_store_search_optional_params,- api_base=api_base,- litellm_logging_obj=logging_obj,- litellm_params=dict(litellm_params),- extra_body=extra_body,- router=router,- )+ if isinstance(vector_store_provider_config, BaseQueryEmbeddingVectorStoreConfig):+ (+ url,+ request_body,+ ) = vector_store_provider_config.transform_search_vector_store_request(+ vector_store_id=vector_store_id,+ query=query,+ vector_store_search_optional_params=vector_store_search_optional_params,+ api_base=api_base,+ litellm_logging_obj=logging_obj,+ litellm_params=dict(litellm_params),+ extra_body=extra_body,++ router=router,+ embedding_executor=embedding_executor,+ )+ else:+ (+ url,+ request_body,+ ) = vector_store_provider_config.transform_search_vector_store_request(+ vector_store_id=vector_store_id,+ query=query,+ vector_store_search_optional_params=vector_store_search_optional_params,+ api_base=api_base,+ litellm_logging_obj=logging_obj,+ litellm_params=dict(litellm_params),+ extra_body=extra_body,++ router=router,+ )all_optional_params: Final[dict[str, object]] = dict(litellm_params)all_optional_params.update(vector_store_search_optional_params or {})diff --cc litellm/llms/milvus/vector_stores/transformation.pyindex b0291c692d5,c3581abfbcc..4f3c366d8c1--- a/litellm/llms/milvus/vector_stores/transformation.py+++ b/litellm/llms/milvus/vector_stores/transformation.py@@@ -1,4 -1,3 +1,6 @@@++from __future__ import annotations+++from collections.abc import Mapping, Sequencefrom typing import TYPE_CHECKING, Any, Finalimport httpx@@@ -124,67 -122,53 +127,69 @@@ class MilvusVectorStoreConfig(BaseQueryvector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,api_base: str,litellm_logging_obj: LiteLLMLoggingObj,- litellm_params: dict,- extra_body: dict[str, Any] | None = None,- router: "Router | None" = None,- ) -> tuple[str, dict[str, Any]]:- """- Transform search request for Azure AI Search API-- Generates embeddings using litellm.embeddings and constructs Azure AI Search request- """- # Convert query to string if it's a list- if isinstance(query, list):- query = " ".join(query)-- # Get embedding model from litellm_params (required)- embedding_model: Final = litellm_params.get("litellm_embedding_model")- if not embedding_model:- raise ValueError(- "embedding_model is required in litellm_params for Milvus. You can call any litellm embedding model."- "Example: litellm_params['embedding_model'] = 'azure/text-embedding-3-large'"- )-- embedding_config: Final = litellm_params.get("litellm_embedding_config", {})- if not embedding_config:- raise ValueError(- "embedding_config is required in litellm_params for Milvus. You can call any litellm embedding model."- "Example: litellm_params['embedding_config'] = {'api_base': 'https://krris-mh44uf7y-eastus2.cognitiveservices.azure.com/', 'api_key': 'os.environ/AZURE_API_KEY', 'api_version': '2025-09-01'}"- )-- # Get top_k (number of results to return)- # Generate embedding for the query using litellm.embeddings- try:- embedding_response: Final = litellm.embedding(- model=embedding_model,- input=[query],- **embedding_config,+ litellm_params: Mapping[str, object],+ extra_body: Mapping[str, object] | None = None,++ router: Router | None = None,+ embedding_executor: VectorStoreEmbeddingExecutor | None = None,+ ) -> tuple[str, dict[str, object]]:+ query_text: Final = self.query_text(query)- query_vector: Final = self.embed_query(query_text, litellm_params, embedding_executor)++ query_vector: Final = self.embed_query(query_text, litellm_params, embedding_executor, router)+ return self._search_request(+ vector_store_id,+ query_text,+ query_vector,+ vector_store_search_optional_params,+ api_base,+ litellm_logging_obj,+ litellm_params,+ )++ async def atransform_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,+ embedding_executor: VectorStoreEmbeddingExecutor | None = None,+ ) -> tuple[str, dict[str, object]]:+ query_text: Final = self.query_text(query)- query_vector: Final = await self.aembed_query(query_text, litellm_params, embedding_executor)++ query_vector: Final = await self.aembed_query(query_text, litellm_params, embedding_executor, router)+ return self._search_request(+ vector_store_id,+ query_text,+ query_vector,+ vector_store_search_optional_params,+ api_base,+ litellm_logging_obj,+ litellm_params,+ )++ @staticmethod+ def _search_request(+ vector_store_id: str,+ query_text: str,+ query_vector: Sequence[float],+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,+ api_base: str,+ litellm_logging_obj: LiteLLMLoggingObj,+ litellm_params: Mapping[str, object],+ ) -> tuple[str, dict[str, object]]:+ scope: Final = {+ key: value+ for key, value in (+ ("dbName", litellm_params.get("milvus_db_name")),+ ("partitionNames", litellm_params.get("milvus_partition_names")),)- query_vector: Final = embedding_response.data[0]["embedding"]- except Exception as e:- raise Exception(f"Failed to generate embedding for query: {e}")-- # Azure AI Search endpoint for search- index_name: Final = vector_store_id # vector_store_id is the index name- url: Final = f"{api_base}/v2/vectordb/entities/search"-- # Build the request body for Azure AI Search with vector search- request_body: Final[dict[str, Any]] = {- "collectionName": index_name,+ if value+ }+ litellm_logging_obj.model_call_details["input"] = query_text+ litellm_logging_obj.model_call_details["embedding_model"] = litellm_params.get("litellm_embedding_model")+ return f"{api_base}/v2/vectordb/entities/search", {+ "collectionName": vector_store_id,"data": [query_vector],"annsField": "book_intro_vector",**vector_store_search_optional_params,diff --cc litellm/proxy/rag_endpoints/endpoints.pyindex db574f859b3,0ab7d99e4e4..e144ff965ae--- a/litellm/proxy/rag_endpoints/endpoints.py+++ b/litellm/proxy/rag_endpoints/endpoints.py@@@ -705,6 -723,21 +723,21 @@@ 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: the same source the direct+ # /vector_stores/{id}/search endpoint uses. Store-managed keys win on+ # conflict so callers cannot override the store's provider or credentials.+ managed_store: Final = resolved_stores.get(retrieval_config["vector_store_id"])+ store_data: Final = (- await build_request_data_from_managed_vector_store(managed_store)++ build_request_data_from_managed_vector_store(managed_store)+ if managed_store is not None+ else MappingProxyType({})+ )+ merged_retrieval_config: Final = {+ **retrieval_config,+ **store_data,+ } # mutable-ok: litellm.aquery requires a plain dict payload+# Add litellm datarequest_data: dict[str, object] = {}request_data = await add_litellm_data_to_request(diff --cc litellm/proxy/vector_store_endpoints/endpoints.pyindex 3fc67181d5b,7d64e648e08..1feda0b0bb5--- a/litellm/proxy/vector_store_endpoints/endpoints.py+++ b/litellm/proxy/vector_store_endpoints/endpoints.py@@@ -29,6 -57,41 +54,20 @@@ def reject_caller_embedding_selection_p########################################################-async def build_request_data_from_managed_vector_store(++def build_request_data_from_managed_vector_store(+ vector_store: LiteLLM_ManagedVectorStore,+ ) -> Mapping[str, object]:- """- Build request params (provider, credential ref, litellm_params) from an- already-resolved managed vector store.-- ``litellm_embedding_config`` is resolved here, at request-handling time,- instead of at row-creation time: the resolved api_key/api_base/api_version- lives only in the returned per-request mapping and is never persisted back- to the registry cache. Legacy rows that already carry a resolved- (cleartext) config skip the lookup and pass through unchanged.- """+ top_level: Final = MappingProxyType(+ {+ key: vector_store.get(key)+ for key in ("custom_llm_provider", "litellm_credential_name")+ if key in vector_store+ }+ )+ litellm_params: Final = vector_store.get("litellm_params") or MappingProxyType({})- embedding_model: Final = litellm_params.get("litellm_embedding_model")- if not embedding_model or litellm_params.get("litellm_embedding_config"):- return MappingProxyType({**top_level, **litellm_params})-- from litellm.proxy.proxy_server import prisma_client-- resolved_config: Final = await _resolve_embedding_config(- embedding_model=embedding_model, prisma_client=prisma_client- )- if not resolved_config:- return MappingProxyType({**top_level, **litellm_params})- return MappingProxyType({**top_level, **litellm_params, "litellm_embedding_config": resolved_config})++ return MappingProxyType({**top_level, **litellm_params})++async def _update_request_data_with_litellm_managed_vector_store_registry(data: dict,vector_store_id: str,@@@ -48,25 -111,14 +87,14 @@@vector_store_to_run: Final[LiteLLM_ManagedVectorStore | None] = await get_litellm_managed_vector_store(vector_store_id=vector_store_id)- if vector_store_to_run is not None:- if user_api_key_dict is not None:- await assert_user_can_access_vector_store(- vector_store=vector_store_to_run,- user_api_key_dict=user_api_key_dict,- )-- if "custom_llm_provider" in vector_store_to_run:- data["custom_llm_provider"] = vector_store_to_run.get("custom_llm_provider")-- if "litellm_credential_name" in vector_store_to_run:- data["litellm_credential_name"] = vector_store_to_run.get("litellm_credential_name")-- if "litellm_params" in vector_store_to_run:- litellm_params: Final = (- vector_store_to_run.get("litellm_params", {}) or {}- ) # mutable-ok: request execution merges persisted params into a mutable body- data.update(litellm_params)- return data+ if vector_store_to_run is None:+ return data+ if user_api_key_dict is not None:+ await assert_user_can_access_vector_store(+ vector_store=vector_store_to_run,+ user_api_key_dict=user_api_key_dict,+ )- return {**data, **(await build_request_data_from_managed_vector_store(vector_store_to_run))}++ return {**data, **build_request_data_from_managed_vector_store(vector_store_to_run)}@router.post(diff --cc litellm/proxy/vector_store_endpoints/management_endpoints.pyindex 8ca45f736ae,244798ba05e..c928398a87f--- a/litellm/proxy/vector_store_endpoints/management_endpoints.py+++ b/litellm/proxy/vector_store_endpoints/management_endpoints.py@@@ -212,10 -469,10 +212,9 @@@ async def create_vector_store_in_db# (``api_key``, ``api_base``, ``api_version``) into this row. That# exposed every env-stored embedding-model credential on the# ``/vector_store/{new,info,update,list}`` responses. Keep the user's-- # raw ``litellm_embedding_model`` reference; resolution now happens in- # ``_update_request_data_with_litellm_managed_vector_store_registry``- # ``build_request_data_from_managed_vector_store``-- # at request-handling time so the cleartext config exists only in-- # per-request memory and never reaches the database.++ # raw ``litellm_embedding_model`` reference; each search embeds the++ # query through the router at request time, so the credentials stay++ # on the deployment and never reach the database.if litellm_params:litellm_params_dict: Final = GenericLiteLLMParams(**litellm_params).model_dump(exclude_none=True)data_to_create["litellm_params"] = safe_dumps(litellm_params_dict)@@@ -605,11 -862,11 +604,9 @@@ async def update_vector_store# Handle litellm_params if provided. As with the create path, the# embedding-config auto-resolve previously persisted cleartext-- # credentials into the row; resolution now happens at request--- # handling time in- # ``_update_request_data_with_litellm_managed_vector_store_registry``- # ``build_request_data_from_managed_vector_store``-- # so this row only ever stores the user-supplied-- # ``litellm_embedding_model`` reference.++ # credentials into the row; each search now embeds the query++ # through the router at request time, so this row only ever stores++ # the user-supplied ``litellm_embedding_model`` reference.if "litellm_params" in update_data:_input_litellm_params: Final[dict] = update_data.get("litellm_params", {}) or {}litellm_params_dict: Final = GenericLiteLLMParams(**_input_litellm_params).model_dump(exclude_none=True)diff --cc litellm/router.pyindex 9e0e267f21c,b1285f9e55e..991f1bc2828--- a/litellm/router.py+++ b/litellm/router.py@@@ -6366,11 -6446,16 +6449,29 @@@ class Routerclient: object | None = None,**kwargs,):- if custom_llm_provider and "custom_llm_provider" not in kwargs:- kwargs["custom_llm_provider"] = custom_llm_provider- if kwargs.get("model"):- return self._generic_api_call_with_fallbacks(original_function=original_function, **kwargs)- return original_function(**kwargs)+ provider_kwargs: Final = (+ MappingProxyType({**kwargs, "custom_llm_provider": custom_llm_provider})+ if custom_llm_provider and "custom_llm_provider" not in kwargs+ else MappingProxyType(kwargs)+ )- if provider_kwargs.get("model"):- return self._generic_api_call_with_fallbacks(original_function=original_function, **provider_kwargs)++ search_kwargs: Final = (++ MappingProxyType(++ {++ **provider_kwargs,++ "_direct_vector_store_embedding_executor": RouterVectorStoreEmbeddingExecutor(++ router=self,++ metadata=self._vector_store_request_metadata(kwargs),++ ),++ }++ )++ if call_type == "vector_store_search"++ else provider_kwargs++ )++ if search_kwargs.get("model"):++ return self._generic_api_call_with_fallbacks(original_function=original_function, **search_kwargs)+ if call_type == "vector_store_search":- return original_function(**MappingProxyType({**provider_kwargs, "router": self}))- return original_function(**provider_kwargs)++ return original_function(**MappingProxyType({**search_kwargs, "router": self}))++ return original_function(**search_kwargs)return vector_store_sync_wrapper@@@ -6557,7 -6631,8 +6658,8 @@@return await self._init_vector_store_api_endpoints(original_function=original_function,custom_llm_provider=custom_llm_provider,+ call_type=call_type,- **kwargs,+ **vector_store_kwargs,)elif call_type in ("afile_delete", "afile_content"):return await self._ageneric_api_call_with_fallbacks(diff --cc litellm/vector_stores/main.pyindex 89c3319ca5a,cd576755f5f..ade4d19815b--- a/litellm/vector_stores/main.py+++ b/litellm/vector_stores/main.py@@@ -325,7 -312,7 +329,8 @@@ async def asearchextra_body=extra_body,timeout=timeout,custom_llm_provider=custom_llm_provider,+ _direct_vector_store_embedding_executor=embedding_executor,+ router=router,**kwargs,)diff --cc tests/test_litellm/proxy/vector_store_endpoints/test_vector_store_endpoints.pyindex 903d5cb55f3,45a0221c8a6..854ce351f2d--- a/tests/test_litellm/proxy/vector_store_endpoints/test_vector_store_endpoints.py+++ b/tests/test_litellm/proxy/vector_store_endpoints/test_vector_store_endpoints.py@@@ -50,111 -51,17 +50,113 @@@ def _serialize_litellm_params(litellm_preturn json.dumps(litellm_params or {})[email protected](autouse=True)-def _reset_embedding_config_cache():- """The use-time embedding-config resolver caches results in process- memory across calls. Reset it before every test so the resolver- actually exercises the router/DB path under test instead of returning- a value cached by an earlier test."""- from litellm.proxy.vector_store_endpoints import management_endpoints+def test_direct_vector_store_embedding_executor_rejects_invalid_value():+ with pytest.raises(TypeError, match="Invalid direct vector store embedding executor"):+ _direct_vector_store_embedding_executor(object())- management_endpoints._embedding_config_cache = None- yield- management_endpoints._embedding_config_cache = None++def test_router_vector_store_search_injects_executor_and_request_metadata():+ router = litellm.Router(model_list=[])+ original = MagicMock(return_value="searched")+ wrapped = router.factory_function(original, call_type="vector_store_search")++ assert (+ wrapped(+ vector_store_id="store",+ query="query",+ custom_llm_provider="valkey",+ litellm_metadata={"user_api_key_team_id": "team-a"},+ )+ == "searched"+ )++ call_kwargs = original.call_args.kwargs+ assert call_kwargs["custom_llm_provider"] == "valkey"+ executor = call_kwargs["_direct_vector_store_embedding_executor"]+ assert isinstance(executor, RouterVectorStoreEmbeddingExecutor)+ assert executor.metadata == {"user_api_key_team_id": "team-a"}+ assert litellm.Router._vector_store_request_metadata({"metadata": {"user_api_key_team_id": "team-b"}}) == {+ "user_api_key_team_id": "team-b"+ }+ assert litellm.Router._vector_store_request_metadata({}) == {}++ with patch.object( # test-quality-ok: fallback dispatch is the boundary this wrapper delegates to+ router, "_generic_api_call_with_fallbacks", return_value="routed"+ ) as fallback:+ assert wrapped(model="vector-alias", vector_store_id="store", query="query") == "routed"+ assert fallback.call_args.kwargs["model"] == "vector-alias"+ assert fallback.call_args.kwargs["original_function"] is original+- create_original = MagicMock()++ create_original = MagicMock(return_value="created")+ wrapped_create = router.factory_function(create_original, call_type="vector_store_create")++ assert wrapped_create(name="store") == "created"++ create_original.assert_called_once_with(name="store")+ with patch.object( # test-quality-ok: fallback dispatch is the boundary this wrapper delegates to- router, "_generic_api_call_with_fallbacks", return_value="created"++ router, "_generic_api_call_with_fallbacks", return_value="created-through-router"+ ) as fallback:- assert wrapped_create(name="store") == "created"- fallback.assert_called_once_with(original_function=create_original, name="store")++ assert wrapped_create(model="vector-alias", name="store") == "created-through-router"++ fallback.assert_called_once_with(original_function=create_original, model="vector-alias", name="store")+++async def test_vector_store_embedding_executors_preserve_explicit_configuration():+ response = EmbeddingResponse(data=[{"embedding": [0.1], "index": 0, "object": "embedding"}])+ sdk_executor = LiteLLMVectorStoreEmbeddingExecutor()++ with (+ patch( # test-quality-ok: isolates SDK dispatch from external embedding providers+ "litellm.embedding", return_value=response+ ) as embedding,+ patch( # test-quality-ok: isolates async SDK dispatch from external embedding providers+ "litellm.aembedding", new=AsyncMock(return_value=response)+ ) as aembedding,+ ):+ assert sdk_executor.embed("openai/model", "sync", {"api_key": "explicit"}) is response+ assert await sdk_executor.aembed("openai/model", "async", {"api_key": "explicit"}) is response++ embedding.assert_called_once_with(model="openai/model", input=["sync"], api_key="explicit")+ aembedding.assert_awaited_once_with(model="openai/model", input=["async"], api_key="explicit")++ mock_router = MagicMock()+ mock_router.embedding.return_value = response+ mock_router.aembedding = AsyncMock(return_value=response)+ router_executor = RouterVectorStoreEmbeddingExecutor(+ router=mock_router,+ metadata={"user_api_key_team_id": "team-a"},+ )++ assert router_executor.embed("team-alias", "query", {}) is response+ mock_router.embedding.assert_called_once_with(+ model="team-alias",+ input=["query"],+ metadata={"user_api_key_team_id": "team-a"},+ )++ with (+ patch( # test-quality-ok: verifies explicit store configuration at the SDK boundary+ "litellm.embedding", return_value=response+ ) as explicit_embedding,+ patch( # test-quality-ok: verifies async explicit store configuration at the SDK boundary+ "litellm.aembedding", new=AsyncMock(return_value=response)+ ) as explicit_aembedding,+ ):+ assert router_executor.embed("openai/model", "query", {"api_key": "store-key"}) is response+ assert await router_executor.aembed("openai/model", "query", {"api_key": "store-key"}) is response++ explicit_embedding.assert_not_called()+ explicit_aembedding.assert_not_awaited()+ assert mock_router.embedding.call_args.kwargs == {+ "model": "openai/model",+ "input": ["query"],+ "api_key": "store-key",+ "metadata": {"user_api_key_team_id": "team-a"},+ }+ mock_router.aembedding.assert_awaited_once_with(+ model="openai/model",+ input=["query"],+ api_key="store-key",+ metadata={"user_api_key_team_id": "team-a"},+ )@pytest.mark.asyncio