Skip to content

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]

merge: resolve MongoDB sidecar staging conflicts

Yuneng Jiang5c55ad7db0c6
diff --cc litellm/llms/custom_httpx/llm_http_handler.py
index 1dc4b198890,8b6d3a0ceb4..7587b963a38
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@@ -9814,7 -9826,7 +9826,7 @@@ class BaseLLMHTTPHandler
vector_store_search_optional_params=vector_store_search_optional_params,
api_base=api_base,
litellm_logging_obj=logging_obj,
- litellm_params={**dict(litellm_params), "timeout": timeout},
- litellm_params=dict(litellm_params),
++ litellm_params=MappingProxyType(dict(litellm_params, timeout=timeout)),
extra_body=extra_body,
embedding_executor=embedding_executor,
)
@@@ -9859,10 -9871,6 +9871,12 @@@
data=request_data,
timeout=timeout,
)
+ except httpx.TimeoutException:
+ raise vector_store_provider_config.get_error_class(
- error_message="Vector store search exceeded the caller timeout.", status_code=408, headers={}
++ error_message="Vector store search exceeded the caller timeout.",
++ status_code=408,
++ headers=httpx.Headers(),
+ ) from None
except Exception as e:
raise self._handle_error(e=e, provider_config=vector_store_provider_config)
@@@ -9947,7 -9955,7 +9961,7 @@@
vector_store_search_optional_params=vector_store_search_optional_params,
api_base=api_base,
litellm_logging_obj=logging_obj,
- litellm_params={**dict(litellm_params), "timeout": timeout},
- litellm_params=dict(litellm_params),
++ litellm_params=MappingProxyType(dict(litellm_params, timeout=timeout)),
extra_body=extra_body,
embedding_executor=embedding_executor,
)
@@@ -9992,12 -10000,7 +10006,14 @@@
url=url,
headers=headers,
data=request_data,
+ timeout=timeout,
)
+ except httpx.TimeoutException:
+ raise vector_store_provider_config.get_error_class(
- error_message="Vector store search exceeded the caller timeout.", status_code=408, headers={}
++ error_message="Vector store search exceeded the caller timeout.",
++ status_code=408,
++ headers=httpx.Headers(),
+ ) from None
except Exception as e:
raise self._handle_error(e=e, provider_config=vector_store_provider_config)
diff --cc litellm/llms/mongodb/vector_stores/transformation.py
index 606da9cffb4,3382c931c96..a59f39d3be8
--- a/litellm/llms/mongodb/vector_stores/transformation.py
+++ b/litellm/llms/mongodb/vector_stores/transformation.py
@@@ -45,31 -59,6 +45,31 @@@ _SEARCH_ONLY_MESSAGE: Final =
)
+def config_error(message: str) -> BadRequestError:
+ return BadRequestError(message=message, model=None, llm_provider="mongodb")
+
+
+class _Content(BaseModel):
+ model_config = ConfigDict(frozen=True, strict=True)
+ type: Literal["text"]
+ text: str
+
+
+class _Result(BaseModel):
+ model_config = ConfigDict(frozen=True, strict=True, allow_inf_nan=False)
+ score: float | None
- content: list[_Content]
++ content: Sequence[_Content]
+ file_id: str | None
+ filename: str | None
+
+
+class _SearchResponse(BaseModel):
+ model_config = ConfigDict(frozen=True, strict=True)
+ object: Literal["vector_store.search_results.page"]
+ search_query: str
- data: list[_Result]
++ data: Sequence[_Result]
+
+
class _MongoDBSearchParams(BaseModel):
"""Typed view over the vector store's litellm_params; unrelated keys are ignored."""
@@@ -184,196 -191,239 +184,203 @@@ class MongoDBVectorStoreConfig(BaseQuer
return configured
return min(max(limit * NUM_CANDIDATES_MULTIPLIER, MIN_NUM_CANDIDATES), MAX_NUM_CANDIDATES)
- @staticmethod
- def _timeout_ms(timeout: float | httpx.Timeout | None) -> tuple[int, int]:
- """The connect and socket budgets pymongo is built with, in that order."""
- if isinstance(timeout, httpx.Timeout):
- return (
- int((timeout.connect or DEFAULT_CONNECT_TIMEOUT_MS / 1000) * 1000),
- int((timeout.read or DEFAULT_SOCKET_TIMEOUT_MS / 1000) * 1000),
+ def validate_environment(
- self, headers: dict[str, object], litellm_params: GenericLiteLLMParams | None
- ) -> dict[str, object]:
++ self, headers: Mapping[str, object], litellm_params: GenericLiteLLMParams | None
++ ) -> dict[str, object]: # mutable-ok: the shared HTTP handler requires writable headers
+ if litellm_params is None:
+ raise config_error("Configure api_base and api_key for the MongoDB BETA sidecar.")
- self._reject_unknown_params(dict(litellm_params))
++ self._reject_unknown_params(MappingProxyType(dict(litellm_params)))
+ api_key: Final = litellm_params.api_key or get_secret_str("MONGODB_SIDECAR_API_KEY")
+ if not api_key:
+ raise config_error("MongoDB sidecar api_key is required. Set api_key or MONGODB_SIDECAR_API_KEY.")
- return {**headers, "Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
++ return {
++ **headers,
++ "Authorization": f"Bearer {api_key}",
++ "Content-Type": "application/json",
++ } # mutable-ok: writable HTTP headers
+
- def get_complete_url(self, api_base: str | None, litellm_params: dict[str, object]) -> str:
++ def get_complete_url(self, api_base: str | None, litellm_params: Mapping[str, object]) -> str:
+ if not api_base:
+ raise config_error("MongoDB sidecar api_base is required, for example http://127.0.0.1:8080.")
+ try:
+ parsed: Final = urlsplit(api_base)
+ valid: Final = parsed.scheme in ("http", "https") and bool(parsed.hostname) and parsed.port != 0
+ except ValueError:
+ raise config_error("MongoDB sidecar api_base must be a valid HTTP or HTTPS URL.") from None
+ if not valid or parsed.username or parsed.password or parsed.query or parsed.fragment:
+ raise config_error(
+ "MongoDB sidecar api_base must be an HTTP or HTTPS URL without credentials, query, or fragment."
)
- if timeout is None:
- return DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_SOCKET_TIMEOUT_MS
- return min(int(float(timeout) * 1000), DEFAULT_CONNECT_TIMEOUT_MS), int(float(timeout) * 1000)
+ if parsed.scheme == "http":
+ try:
+ loopback: Final = ip_address(parsed.hostname or "").is_loopback
+ except ValueError:
+ raise config_error(
+ "MongoDB sidecar requires HTTPS. HTTP is supported only for a loopback IP such as 127.0.0.1."
+ ) from None
+ if not loopback:
+ raise config_error(
+ "MongoDB sidecar requires HTTPS. HTTP is supported only for a loopback IP such as 127.0.0.1."
+ )
+ return api_base.rstrip("/")
- @classmethod
- def _client_key(cls, params: _MongoDBSearchParams, timeout: float | httpx.Timeout | None) -> MongoClientKey:
- connect_ms, socket_ms = cls._timeout_ms(timeout)
- return MongoClientKey(
- connection_string=params.require_connection_string(),
- connect_timeout_ms=connect_ms,
- socket_timeout_ms=socket_ms,
- server_selection_timeout_ms=min(connect_ms, DEFAULT_SERVER_SELECTION_TIMEOUT_MS),
- )
+ @staticmethod
+ def _timeout_ms(value: object) -> int:
+ seconds: Final = value.read if isinstance(value, httpx.Timeout) else value
+ if seconds is None:
+ return 30_000
+ if not isinstance(seconds, (int, float)) or not isfinite(seconds) or seconds <= 0:
+ raise config_error("MongoDB search timeout must be a positive finite number.")
+ try:
+ return max(1, int(seconds * 1000))
+ except (ValueError, OverflowError):
+ raise config_error("MongoDB search timeout must be a positive finite number.") from None
@classmethod
- def _pipeline(
+ def _params(
cls,
- vector_store_id: str,
- query_vector: Sequence[float],
- params: _MongoDBSearchParams,
- vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,
- ) -> Sequence[Mapping[str, object]]:
- if vector_store_search_optional_params.get("filters") is not None:
- raise config_error(
- "MongoDB vector store does not support the filters parameter yet. "
- "Restrict the collection or the MongoDB Vector Search index definition instead."
- )
- if vector_store_search_optional_params.get("ranking_options") is not None:
- raise config_error(
- "MongoDB vector store does not support the ranking_options parameter yet. "
- "Every result already carries the vectorSearchScore, so filter or re-rank "
- "on that rather than having the threshold silently ignored."
- )
- if vector_store_search_optional_params.get("rewrite_query") is not None:
+ litellm_params: Mapping[str, object],
+ optional_params: VectorStoreSearchOptionalRequestParams,
+ extra_body: Mapping[str, object] | None,
+ ) -> _MongoDBSearchParams:
+ cls._reject_unknown_params(litellm_params)
+ if extra_body:
+ raise config_error("MongoDB vector store does not support extra_body overrides.")
+ for unsupported in ("filters", "ranking_options", "rewrite_query"):
+ if optional_params.get(unsupported) is not None:
+ raise config_error(f"MongoDB vector store does not support the {unsupported} parameter.")
+ try:
+ params: Final = _MongoDBSearchParams.model_validate(litellm_params)
+ except ValidationError:
raise config_error(
- "MongoDB vector store does not support the rewrite_query parameter. The query is "
- "embedded exactly as sent; rewrite it before calling if you need that."
- )
- limit: Final = cls._limit(vector_store_search_optional_params)
- search: Final = MappingProxyType(
- {
- "index": vector_store_id,
- "path": params.embedding_field,
- "queryVector": tuple(query_vector),
- "numCandidates": cls._num_candidates(limit, params.mongodb_num_candidates),
- "limit": limit,
- }
- )
- projection: Final = MappingProxyType(
- {params.text_field: 1, SCORE_FIELD_NAME: MappingProxyType({"$meta": "vectorSearchScore"})}
- )
- return [ # mutable-ok: pymongo rejects any non-list pipeline in common.validate_list
- MappingProxyType({"$vectorSearch": search}),
- MappingProxyType({"$project": projection}),
- ]
-
- @classmethod
- def _field_value(cls, document: Mapping[str, object], dotted_path: str) -> str | None:
- """None means absent, which is what separates a mistyped field from genuinely empty text."""
- head, _, rest = dotted_path.partition(".")
- if head not in document:
- return None
- value: Final = document[head]
- if not rest:
- return None if value is None else str(value)
- return cls._field_value(value, rest) if isinstance(value, Mapping) else None
-
- @classmethod
- def _to_result(cls, document: Mapping[str, object], text_field: str) -> VectorStoreSearchResult:
- document_id: Final = document.get("_id")
- identifier: Final = None if document_id is None else str(document_id)
- content: Final = [ # mutable-ok: VectorStoreSearchResult declares a list of content parts
- VectorStoreResultContent(text=cls._field_value(document, text_field) or "", type="text")
- ]
- raw_score: Final = document.get(SCORE_FIELD_NAME)
- return VectorStoreSearchResult(
- score=float(raw_score) if isinstance(raw_score, (int, float)) else None,
- content=content,
- file_id=identifier,
- filename=identifier,
- )
+ "Invalid MongoDB vector-store configuration. Check the database, collection, fields, and candidate count."
+ ) from None
+ params.require_database()
+ params.require_collection()
+ params.require_embedding_model()
+ cls._num_candidates(cls._limit(optional_params), params.mongodb_num_candidates)
+ cls._timeout_ms(litellm_params.get("timeout"))
+ return params
@classmethod
- def _raise_for_missing_text_field(
- cls, documents: Sequence[Mapping[str, object]], text_field: str, database: str, collection: str
- ) -> None:
- """$vectorSearch matches documents carrying no text, so a mistyped mongodb_text_field
- returns well-scored results with empty content instead of failing."""
- if documents and all(cls._field_value(document, text_field) is None for document in documents):
+ def _request(
+ cls,
+ vector_store_id: str,
+ query_text: str,
+ params: _MongoDBSearchParams,
+ optional_params: VectorStoreSearchOptionalRequestParams,
+ api_base: str,
+ embedding_response: EmbeddingResponse,
+ timeout: object,
- ) -> tuple[str, dict[str, object]]:
++ ) -> tuple[str, dict[str, object]]: # mutable-ok: the provider contract returns a writable JSON request body
+ if not embedding_response.data:
raise config_error(
- f"None of the {len(documents)} matched documents in '{database}.{collection}' has a "
- f"'{text_field}' field, so every result would carry empty text. Set mongodb_text_field "
- "to the field holding the readable text; it accepts a dotted path such as metadata.body."
+ "The embedding model returned no embedding for the search query. Check litellm_embedding_model."
)
-
- @classmethod
- def _to_response(
- cls, documents: Sequence[Mapping[str, object]], query_text: str, text_field: str
- ) -> VectorStoreSearchResponse:
- return VectorStoreSearchResponse(
- object="vector_store.search_results.page",
- search_query=query_text,
- data=[ # mutable-ok: VectorStoreSearchResponse declares data as a list
- cls._to_result(document, text_field) for document in documents
- ],
+ vector: Final = embedding_response.data[0]["embedding"]
+ if not vector or any(not isinstance(value, (float, int)) or not isfinite(value) for value in vector):
+ raise config_error("The embedding model must return a non-empty, finite query vector.")
+ limit: Final = cls._limit(optional_params)
- return f"{api_base}/v1/vector_stores/{quote(vector_store_id, safe='')}/search", {
- "query": query_text,
- "query_vector": tuple(vector),
- "mongodb_database": params.require_database(),
- "mongodb_collection": params.require_collection(),
- "mongodb_embedding_field": params.embedding_field,
- "mongodb_text_field": params.text_field,
- "mongodb_num_candidates": cls._num_candidates(limit, params.mongodb_num_candidates),
- "max_num_results": limit,
- "timeout_ms": cls._timeout_ms(timeout),
- }
++ return (
++ f"{api_base}/v1/vector_stores/{quote(vector_store_id, safe='')}/search",
++ { # mutable-ok: JSON transport requires a dict
++ "query": query_text,
++ "query_vector": tuple(vector),
++ "mongodb_database": params.require_database(),
++ "mongodb_collection": params.require_collection(),
++ "mongodb_embedding_field": params.embedding_field,
++ "mongodb_text_field": params.text_field,
++ "mongodb_num_candidates": cls._num_candidates(limit, params.mongodb_num_candidates),
++ "max_num_results": limit,
++ "timeout_ms": cls._timeout_ms(timeout),
++ },
+ )
- @staticmethod
- def _raise_for_unusable_index(
- catalogue: Sequence[Mapping[str, object]], index_name: str, database: str, collection: str
- ) -> None:
- """mongod returns zero documents both for a query that matched nothing and for a missing
- database, collection or index, so the catalogue decides which one happened."""
- if not catalogue:
- raise missing_index_error(index_name, database, collection)
- entry: Final = catalogue[0]
- if not entry.get("queryable"):
- raise index_not_ready_error(index_name, database, collection, str(entry.get("status") or "unknown"))
-
- @staticmethod
- def _embedding_vector(embedding_response: EmbeddingResponse) -> Sequence[float]:
- data: Final = embedding_response.data
- if not data:
- raise config_error(
- "The embedding model returned no embedding for the search query, so there is nothing "
- "to search MongoDB with. Check the embedding deployment named by litellm_embedding_model."
- )
- return data[0]["embedding"]
-
- def execute_search_vector_store_request(
+ 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,
embedding_executor: VectorStoreEmbeddingExecutor | None = None,
- ) -> tuple[str, dict[str, object]]:
- timeout: float | httpx.Timeout | None = None,
- ) -> VectorStoreSearchResponse:
- self._reject_unknown_params(litellm_params)
- params: Final = _MongoDBSearchParams.model_validate(litellm_params)
++ ) -> tuple[str, dict[str, object]]: # mutable-ok: the provider contract returns a writable JSON request body
+ params: Final = self._params(litellm_params, vector_store_search_optional_params, extra_body)
query_text: Final = self._query_text(query)
- key: Final = self._client_key(params, timeout)
- database: Final = params.require_database()
- collection: Final = params.require_collection()
-
- embedding_response: Final = (embedding_executor or self.embedding_executor).embed(
- params.require_embedding_model(),
- query_text,
- params.litellm_embedding_config or _EMPTY_EMBEDDING_CONFIG,
+ response: Final = (embedding_executor or self.embedding_executor).embed(
+ params.require_embedding_model(), query_text, params.litellm_embedding_config or _EMPTY_EMBEDDING_CONFIG
)
- pipeline: Final = self._pipeline(
- vector_store_id, self._embedding_vector(embedding_response), params, vector_store_search_optional_params
+ return self._request(
+ vector_store_id,
+ query_text,
+ params,
+ vector_store_search_optional_params,
+ api_base,
+ response,
+ litellm_params.get("timeout"),
)
- try:
- client: Final = self.sync_client_factory(key)
- target: Final = client[database][collection] # pyright: ignore[reportIndexIssue] # factory is typed as returning object so injected doubles are accepted
- documents: Final = tuple(target.aggregate(pipeline))
- except Exception as e:
- raise translate_mongo_error(e, index_name=vector_store_id, database=database, collection=collection) from e
- if not documents:
- try:
- catalogue: Final = tuple(target.list_search_indexes(vector_store_id))
- except Exception as e:
- raise translate_mongo_error(
- e, index_name=vector_store_id, database=database, collection=collection
- ) from e
- self._raise_for_unusable_index(catalogue, vector_store_id, database, collection)
- self._raise_for_missing_text_field(documents, params.text_field, database, collection)
- return self._to_response(documents, query_text, params.text_field)
-
- async def aexecute_search_vector_store_request(
+ 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,
embedding_executor: VectorStoreEmbeddingExecutor | None = None,
- ) -> tuple[str, dict[str, object]]:
- timeout: float | httpx.Timeout | None = None,
- ) -> VectorStoreSearchResponse:
- self._reject_unknown_params(litellm_params)
- params: Final = _MongoDBSearchParams.model_validate(litellm_params)
++ ) -> tuple[str, dict[str, object]]: # mutable-ok: the provider contract returns a writable JSON request body
+ params: Final = self._params(litellm_params, vector_store_search_optional_params, extra_body)
query_text: Final = self._query_text(query)
- key: Final = self._client_key(params, timeout)
- database: Final = params.require_database()
- collection: Final = params.require_collection()
-
- embedding_response: Final = await (embedding_executor or self.embedding_executor).aembed(
- params.require_embedding_model(),
- query_text,
- params.litellm_embedding_config or _EMPTY_EMBEDDING_CONFIG,
+ response: Final = await (embedding_executor or self.embedding_executor).aembed(
+ params.require_embedding_model(), query_text, params.litellm_embedding_config or _EMPTY_EMBEDDING_CONFIG
)
- pipeline: Final = self._pipeline(
- vector_store_id, self._embedding_vector(embedding_response), params, vector_store_search_optional_params
+ return self._request(
+ vector_store_id,
+ query_text,
+ params,
+ vector_store_search_optional_params,
+ api_base,
+ response,
+ litellm_params.get("timeout"),
)
+ def transform_search_vector_store_response(
+ self, response: httpx.Response, litellm_logging_obj: "LiteLLMLoggingObj"
+ ) -> VectorStoreSearchResponse:
try:
- client: Final = self.async_client_factory(key)
- target: Final = client[database][collection] # pyright: ignore[reportIndexIssue] # factory is typed as returning object so injected doubles are accepted
- cursor: Final = await target.aggregate(pipeline)
- documents: Final = [ # mutable-ok: an async comprehension cannot build a tuple directly
- document async for document in cursor
- ]
- except Exception as e:
- raise translate_mongo_error(e, index_name=vector_store_id, database=database, collection=collection) from e
- if not documents:
- try:
- index_cursor: Final = await target.list_search_indexes(vector_store_id)
- catalogue: Final = [ # mutable-ok: an async comprehension cannot build a tuple directly
- entry async for entry in index_cursor
- ]
- except Exception as e:
- raise translate_mongo_error(
- e, index_name=vector_store_id, database=database, collection=collection
- ) from e
- self._raise_for_unusable_index(catalogue, vector_store_id, database, collection)
- self._raise_for_missing_text_field(documents, params.text_field, database, collection)
- return self._to_response(documents, query_text, params.text_field)
+ validated: Final = _SearchResponse.model_validate_json(response.content)
+ return _RESPONSE_ADAPTER.validate_python(validated.model_dump())
+ except ValidationError:
+ raise ServiceUnavailableError(
+ message="MongoDB sidecar returned an invalid search response. Check the sidecar version and deployment.",
+ model=None,
+ llm_provider="mongodb",
+ ) from None
+
+ def get_error_class(
- self, error_message: str, status_code: int, headers: dict[str, object] | httpx.Headers
++ self, error_message: str, status_code: int, headers: Mapping[str, object] | httpx.Headers
+ ) -> BaseLLMException:
+ if status_code == 400:
+ raise config_error(error_message)
+ if status_code == 401:
+ raise AuthenticationError(message="MongoDB sidecar rejected api_key.", model=None, llm_provider="mongodb")
+ if status_code == 408:
+ raise Timeout(message=error_message, model=None, llm_provider="mongodb")
+ raise ServiceUnavailableError(
+ message="MongoDB sidecar is unavailable. Check its address, health, and logs.",
+ model=None,
+ llm_provider="mongodb",
+ )
+
+ def validate_create_vector_store(self) -> NoReturn:
+ raise config_error(_SEARCH_ONLY_MESSAGE)
def transform_create_vector_store_request(
- self,
- vector_store_create_optional_params: VectorStoreCreateOptionalRequestParams,
- api_base: str,
+ self, vector_store_create_optional_params: VectorStoreCreateOptionalRequestParams, api_base: str
) -> NoReturn:
raise config_error(_SEARCH_ONLY_MESSAGE)