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 remote-tracking branch 'upstream/litellm_internal_staging' into feat/voyage-context-4

fzowl0769cc2ebc47
diff --cc litellm/llms/voyage/embedding/transformation_contextual.py
index 04cb58bcfcc,ec77ce91d33..d473450a969
--- a/litellm/llms/voyage/embedding/transformation_contextual.py
+++ b/litellm/llms/voyage/embedding/transformation_contextual.py
@@@ -3,9 -3,7 +3,7 @@@ This module is used to transform the re
This would be used for all the contextualized embeddings models in Voyage.
"""
- from __future__ import annotations
-
- from typing import Any
-from typing import Final
++from typing import Any, Final
import httpx
@@@ -84,14 -79,14 +82,14 @@@ class VoyageContextualEmbeddingConfig(B
def validate_environment(
self,
- headers: dict,
+ headers: dict, # mutable-ok: base class signature
model: str,
- messages: list[AllMessageValues], # mutable-ok: base class signature
- optional_params: dict, # mutable-ok: base class signature
- litellm_params: dict, # mutable-ok: base class signature
+ messages: list[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
api_key: str | None = None,
api_base: str | None = None,
- ) -> dict: # mutable-ok: base class signature
+ ) -> dict:
if api_key is None:
api_key = (
get_secret_str("VOYAGE_API_KEY")
@@@ -107,75 -100,15 +105,75 @@@
def transform_embedding_request(
self,
model: str,
- input: AllEmbeddingInputValues | list[list[str]], # mutable-ok: base class signature
- optional_params: dict, # mutable-ok: base class signature
- headers: dict, # mutable-ok: base class signature
- ) -> dict: # mutable-ok: base class signature
+ input: AllEmbeddingInputValues | list[list[str]],
+ optional_params: dict,
+ headers: dict,
+ ) -> dict:
+ inputs, extra_params = self._transform_contextual_inputs(input, optional_params)
return {
- "inputs": input,
+ "inputs": inputs,
"model": model,
**optional_params,
+ **extra_params,
+ }
+
+ @classmethod
+ def _transform_contextual_inputs(
+ cls,
+ input: AllEmbeddingInputValues | list[list[str]], # mutable-ok: union with AllEmbeddingInputValues
+ optional_params: dict, # mutable-ok: matches public API
+ ) -> tuple[list[str] | list[list[str]], dict]: # mutable-ok: returned to caller who owns it
+ """
+ Normalize ``input`` for Voyage's contextualized embeddings API and
+ return ``(inputs, extra_params)`` where ``extra_params`` carries any
+ request fields (e.g. auto-chunking) needed for the chosen shape.
+
+ The API contract (verified against the live endpoint) is:
+
+ - A flat ``list[str]`` is only accepted with ``input_type="query"`` or
+ with ``enable_auto_chunking=True`` (which itself requires
+ ``input_type="document"``).
+ - A ``list[list[str]]`` (each inner list = one document's chunks) is
+ always accepted.
+
+ So we prefer to send a flat ``list[str]`` and let the API auto-chunk,
+ instead of pre-wrapping into ``list[list[str]]``:
+
+ - ``str`` -> ``[str]`` + ``enable_auto_chunking`` (input_type=document)
+ - flat ``list[str]`` + ``input_type="query"`` -> kept flat, as-is
+ - flat ``list[str]`` otherwise -> kept flat + ``enable_auto_chunking``
+ (input_type=document)
+ - ``list[list[str]]`` -> passed through unchanged
+
+ Reference: https://docs.voyageai.com/reference/contextualized-embeddings-api
+ """
+ if isinstance(input, str):
+ if optional_params.get("input_type") == "query":
+ return [input], {} # mutable-ok: fresh list returned to caller
+ return [input], cls._auto_chunk_params(optional_params) # mutable-ok: fresh list returned to caller
+
+ if isinstance(input, list) and all(isinstance(i, str) for i in input):
+ if optional_params.get("input_type") == "query":
+ return input, {} # pyright: ignore[reportReturnType] # narrowed to list[str] by isinstance+all check
+ return input, cls._auto_chunk_params(optional_params) # pyright: ignore[reportReturnType] # narrowed to list[str]
+
+ return input, {} # pyright: ignore[reportReturnType] # list[list[str]] branch
+
+ @classmethod
+ def _auto_chunk_params(cls, optional_params: dict) -> dict: # mutable-ok: matches public API
+ """
+ Params required to send a flat ``list[str]`` to the contextualized API.
+
+ ``enable_auto_chunking=True`` requires ``input_type="document"``, so set
+ it unless the caller already provided an ``input_type``.
+ """
+ params: dict[str, Any] = { # mutable-ok: building return value
+ "enable_auto_chunking": True,
+ "chunk_size": cls.AUTO_CHUNK_SIZE,
}
+ if not optional_params.get("input_type"):
+ params["input_type"] = "document"
+ return params
def transform_embedding_response(
self,
@@@ -184,18 -117,16 +182,18 @@@
model_response: EmbeddingResponse,
logging_obj: LiteLLMLoggingObj,
api_key: str | None = None,
- request_data: dict = {}, # mutable-ok: base class signature
- optional_params: dict = {}, # mutable-ok: base class signature
- litellm_params: dict = {}, # mutable-ok: base class signature
+ request_data: dict = {},
+ optional_params: dict = {},
+ litellm_params: dict = {},
) -> EmbeddingResponse:
try:
- raw_response_json = raw_response.json()
+ raw_response_json: Final = raw_response.json()
except Exception:
- raise VoyageError(message=raw_response.text, status_code=raw_response.status_code)
+ raise VoyageError(
+ message=raw_response.text,
+ status_code=raw_response.status_code,
+ )
- # model_response.usage
model_response.model = raw_response_json.get("model")
model_response.data = raw_response_json.get("data")
model_response.object = raw_response_json.get("object")