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: litellm_internal_staging into litellm_vertex_batch_embeddings_translation

milan5b763d6b00df
diff --cc litellm/llms/vertex_ai/files/transformation.py
index 90fc5fae082,f8eea399bf6..9363540fe1b
--- a/litellm/llms/vertex_ai/files/transformation.py
+++ b/litellm/llms/vertex_ai/files/transformation.py
@@@ -5,19 -5,10 +5,11 @@@ import jso
import os
import re
import time
- from collections.abc import Mapping
-from collections.abc import Callable, Iterable, Iterator
++from collections.abc import Callable, Iterable, Iterator, Mapping
from typing import (
Any,
- Callable,
- Dict,
- Iterable,
- Iterator,
- List,
- Optional,
- Tuple,
- Union,
)
+from urllib.parse import quote, unquote
import httpx
from httpx import Headers, Response
@@@ -53,9 -44,7 +45,10 @@@ from litellm.llms.vertex_ai.gemini.tran
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
VertexGeminiConfig,
)
+from litellm.llms.vertex_ai.gemini_embeddings.batch_embed_content_transformation import (
+ transform_openai_input_gemini_embed_content,
+)
+ from litellm.types.files import StreamingMediaUploadConfig
from litellm.types.llms.openai import (
AllMessageValues,
CreateFileRequest,
@@@ -65,15 -54,8 +58,14 @@@
OpenAIFileObject,
PathLike,
)
- from litellm.types.files import StreamingMediaUploadConfig
-from litellm.types.llms.vertex_ai import GcsBucketResponse
-from litellm.types.utils import LlmProviders, ModelResponse
+from litellm.types.llms.vertex_ai import GcsBucketResponse, GeminiEmbeddingInput
+from litellm.types.utils import (
+ Embedding,
+ EmbeddingResponse,
+ LlmProviders,
+ ModelResponse,
+ Usage,
+)
from ..common_utils import VertexAIError
from ..vertex_llm_base import VertexBase
@@@ -150,22 -124,7 +142,22 @@@ def _set_litellm_batch_custom_id_labels
labels[f"litellm_custom_id_raw_{index}"] = raw_label_chunk
+def _get_litellm_batch_custom_id(vertex_output_row: Mapping[str, Any]) -> str:
+ """
+ Resolve the OpenAI `custom_id` for a Vertex batch output row.
+
+ Embedding rows carry it in the top-level `key` field that Vertex echoes back;
+ `generateContent` rows have no such field, so it is smuggled through request
+ labels instead (see `_set_litellm_batch_custom_id_labels`).
+ """
+ key = vertex_output_row.get(_VERTEX_BATCH_KEY_FIELD)
+ if key is not None:
+ return unquote(str(key))
+ request_data = vertex_output_row.get("request") or {}
+ return _get_litellm_batch_custom_id_from_labels(request_data.get("labels") or {})
+
+
- def _get_litellm_batch_custom_id_from_labels(labels: Dict[str, Any]) -> str:
+ def _get_litellm_batch_custom_id_from_labels(labels: dict[str, Any]) -> str:
"""Prefer encoded custom_id when present (see _set_litellm_batch_custom_id_labels)."""
raw = labels.get("litellm_custom_id_raw")
if raw:
@@@ -183,262 -142,12 +175,262 @@@
return str(labels.get("litellm_custom_id", "unknown"))
-def _openai_batch_jsonl_entry_to_vertex_wrapped_request(
+def _is_vertex_embeddings_batch_output_row(vertex_output_row: Mapping[str, Any]) -> bool:
+ """
+ Whether a Vertex batch output row came from an `EmbedContentRequest`.
+
+ Successful rows hold the vector under `response.embedding.values`; failed rows only
+ carry `status`, so they are recognized from the singular `content` that the
+ embeddings request shape echoes back.
+ """
+ if "request" not in vertex_output_row:
+ return False
+ response = vertex_output_row.get("response")
+ if isinstance(response, dict) and isinstance(response.get("embedding"), dict):
+ return True
+ request_data = vertex_output_row.get("request")
+ return bool(vertex_output_row.get("status")) and isinstance(request_data, dict) and "content" in request_data
+
+
+def _openai_batch_output_row(
+ custom_id: str,
+ body: Mapping[str, Any] | None = None,
+ error: Mapping[str, str] | None = None,
+) -> Mapping[str, Any]:
+ """
+ One row of an OpenAI batch output file. Per the OpenAI Batch spec, failed rows set
+ `response` to null and populate `error` instead.
+ """
+ return {
+ "id": f"batch_req_{uuid.uuid4()}",
+ "custom_id": custom_id,
+ "response": None
+ if body is None
+ else {
+ "status_code": 200,
+ "request_id": body.get("id", ""),
+ "body": body,
+ },
+ "error": error,
+ }
+
+
+def _split_vertex_batch_key(vertex_output_row: Mapping[str, Any]) -> tuple[str, int]:
+ """
+ Resolve `(custom_id, index within that custom_id)` for a Vertex batch output row.
+
+ A `/v1/embeddings` entry whose `input` is an array fans out into one Vertex row per
+ element, tagged `<percent-encoded custom_id>#<index>/<total>` (see
+ `_vertex_batch_embeddings_key`), so the rows can be reassembled into a single OpenAI
+ response.
+ """
+ key = vertex_output_row.get(_VERTEX_BATCH_KEY_FIELD)
+ if key is None:
+ return _get_litellm_batch_custom_id(vertex_output_row), 0
+ match = _VERTEX_BATCH_FANNED_OUT_KEY_PATTERN.fullmatch(str(key))
+ if match is None:
+ return unquote(str(key)), 0
+ return unquote(match["custom_id"]), int(match["index"])
+
+
+def _vertex_embeddings_rows_to_openai_batch_output_row(
+ custom_id: str,
+ vertex_output_rows: tuple[Mapping[str, Any], ...],
+ model: str | None,
+) -> Mapping[str, Any]:
+ """
+ Transforms the Vertex Gemini Embedding batch output rows belonging to one OpenAI
+ batch entry into an OpenAI batch output row holding an `/v1/embeddings` response.
+
+ Example Vertex jsonl
+ {"key": "id_1", "request": {...}, "response": {"embedding": {"values": [-0.015, 0.024]}, "usageMetadata": {"promptTokenCount": 2}}}
+
+ An entry that asked for several embeddings at once maps to several rows here, which
+ become the indexed elements of a single `data` array. One failed element fails the
+ whole entry, since an OpenAI batch row is either a response or an error. Live rows
+ report usage under `usageMetadata`; the documented `tokenCount` is kept as a
+ fallback. Rows carry no `modelVersion`, so the model comes from the batch they
+ belong to.
+ """
+ status = next((row["status"] for row in vertex_output_rows if row.get("status")), "")
+ if status:
+ return _openai_batch_output_row(
+ custom_id=custom_id,
+ error={"code": "vertex_ai_error", "message": status},
+ )
+
+ responses = tuple(row.get("response") or {} for row in vertex_output_rows)
+ token_count = sum(
+ int((response.get("usageMetadata") or {}).get("promptTokenCount") or response.get("tokenCount") or 0)
+ for response in responses
+ )
+ body = EmbeddingResponse(
+ model=model or "",
+ data=[
+ Embedding(
+ embedding=response["embedding"]["values"],
+ index=index,
+ object="embedding",
+ )
+ for index, response in enumerate(responses)
+ ],
+ usage=Usage(prompt_tokens=token_count, total_tokens=token_count),
+ ).model_dump()
+ return _openai_batch_output_row(custom_id=custom_id, body=body)
+
+
+def _transform_vertex_embeddings_batch_output_to_openai(
+ vertex_output_rows: Iterable[Mapping[str, Any]],
+ model: str | None,
+) -> tuple[Mapping[str, Any], ...]:
+ """
+ Transforms a whole Vertex Gemini Embedding batch output into OpenAI batch output
+ rows, one per OpenAI batch entry, in the order the entries first appear.
+
+ Rows are grouped rather than mapped one to one because a single entry can fan out
+ into several Vertex rows, and Vertex returns them in arbitrary order.
+ """
+ keyed_rows = tuple((_split_vertex_batch_key(row), row) for row in vertex_output_rows)
+ grouped_rows = {
+ custom_id: tuple(row for _, row in group)
+ for custom_id, group in itertools.groupby(sorted(keyed_rows, key=lambda kr: kr[0]), key=lambda kr: kr[0][0])
+ }
+ return tuple(
+ _vertex_embeddings_rows_to_openai_batch_output_row(
+ custom_id=custom_id,
+ vertex_output_rows=grouped_rows[custom_id],
+ model=model,
+ )
+ for custom_id in dict.fromkeys(custom_id for (custom_id, _), _ in keyed_rows)
+ )
+
+
+def _model_from_managed_gcs_url(url: str) -> str | None:
+ """
+ Extracts the model from a LiteLLM-managed Vertex batch GCS url.
+
+ Batch inputs and their sibling outputs are stored under
+ `.../publishers/google/models/<model>/...`, which is the only place the model of an
+ embeddings batch output row can be recovered from; unlike `generateContent`
+ responses, embedding rows carry no `modelVersion`.
+ """
+ match = _MANAGED_GCS_MODEL_PATH_PATTERN.search(unquote(url))
+ return match.group(1) if match else None
+
+
+def _is_embeddings_batch_entry(openai_entry: Mapping[str, Any]) -> bool:
+ """
+ Whether an OpenAI batch JSONL line targets the embeddings endpoint.
+
+ OpenAI puts the target route on each line's `url` (e.g. `/v1/embeddings`); Vertex
+ has no equivalent per-line field, so the route decides which Vertex request shape
+ the line has to be translated into.
+ """
+ url = openai_entry.get("url")
+ if not isinstance(url, str):
+ return False
+ path = url.split("?")[0].rstrip("/")
+ return path == "embeddings" or path.endswith("/embeddings")
+
+
+def _openai_embedding_input_elements(
+ embedding_input: GeminiEmbeddingInput,
- ) -> tuple[Union[str, List[str]], ...]:
++) -> tuple[str | list[str], ...]:
+ """
+ Split an OpenAI `input` into the elements that each get their own embedding.
+
+ A string is one embedding, a flat array is one embedding per element, and a nested
+ array is one combined embedding per inner array, matching the online
+ `batchEmbedContents` path.
+ """
+ if isinstance(embedding_input, list):
+ return tuple(embedding_input)
+ return (embedding_input,)
+
+
+def _vertex_batch_embeddings_key(custom_id: str, index: int, total: int) -> str:
+ """
+ The top-level `key` Vertex echoes back on an embeddings row.
+
+ An entry asking for several embeddings needs several Vertex rows, so its key also
+ carries the element index and the group size; `_split_vertex_batch_key` reads them
+ back out. The `custom_id` is percent-encoded so that a customer one ending in
+ `#<index>/<total>` cannot be mistaken for that tag, which would merge two entries.
+ """
+ encoded_custom_id = quote(custom_id, safe="")
+ return encoded_custom_id if total < 2 else f"{encoded_custom_id}#{index}/{total}"
+
+
+def _openai_batch_jsonl_entry_to_vertex_embeddings_rows(
+ openai_entry: Mapping[str, Any],
+) -> tuple[Mapping[str, Any], ...]:
+ """
+ Transforms a single OpenAI `/v1/embeddings` batch entry into Vertex Gemini Embedding
+ batch rows, one per requested embedding.
+
+ Example Vertex jsonl
+ {"key": "id_1", "request": {"content": {"parts": [{"text": "Hello World"}]}, "output_dimensionality": 768, "task_type": "RETRIEVAL_DOCUMENT"}}
+
+ Note that `content` is singular (an `EmbedContentRequest`, not a
+ `GenerateContentRequest`) and that the `custom_id` round-trips through the top-level
+ `key`. An `EmbedContentRequest` returns exactly one vector, so an entry whose `input`
+ is an array fans out into one row per element and is reassembled on the way back.
+ The docs put the per-row config in an `embed_content_config` sibling of `request`,
+ but the API rejects that key outright and fails the whole batch job, so the config
+ fields go inside the `EmbedContentRequest` itself.
+
+ API Ref: https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/batch-prediction-genai-embeddings
+ """
+ openai_request_body = openai_entry.get("body") or {}
+ embedding_input = openai_request_body.get("input")
+ if embedding_input is None:
+ raise ValueError("`input` is required on /v1/embeddings batch requests, but was not provided")
+
+ elements = _openai_embedding_input_elements(embedding_input)
+ if not elements:
+ raise ValueError("`input` on /v1/embeddings batch requests must not be empty")
+
+ embed_content_requests = tuple(
+ transform_openai_input_gemini_embed_content(
+ input=element,
+ model=openai_request_body.get("model", ""),
+ optional_params=openai_request_body,
+ )
+ for element in elements
+ )
+ custom_id = openai_entry.get("custom_id")
+ return tuple(
+ {
+ **(
+ {}
+ if custom_id is None
+ else {
+ _VERTEX_BATCH_KEY_FIELD: _vertex_batch_embeddings_key(
+ custom_id=str(custom_id),
+ index=index,
+ total=len(embed_content_requests),
+ )
+ }
+ ),
+ "request": {
+ "content": embed_content_request["content"],
+ **{
+ request_field: embed_content_request[gemini_param]
+ for gemini_param, request_field in _EMBED_REQUEST_FIELD_BY_GEMINI_PARAM.items()
+ if gemini_param in embed_content_request
+ },
+ },
+ }
+ for index, embed_content_request in enumerate(embed_content_requests)
+ )
+
+
+def _openai_batch_jsonl_entry_to_vertex_rows(
- openai_entry: Dict[str, Any],
- map_openai_to_vertex_params: Callable[[Dict[str, Any]], Dict[str, Any]],
+ openai_entry: dict[str, Any],
+ map_openai_to_vertex_params: Callable[[dict[str, Any]], dict[str, Any]],
-) -> dict[str, Any]:
+) -> tuple[Mapping[str, Any], ...]:
"""
- Transforms a single OpenAI JSONL batch entry into its Vertex wrapped request.
+ Transforms a single OpenAI JSONL batch entry into the Vertex rows it maps to.
jsonl body for vertex is {"request": <request_body>}
Example Vertex jsonl
@@@ -463,10 -169,10 +455,10 @@@
vertex_request_body["labels"] = {}
_set_litellm_batch_custom_id_labels(vertex_request_body["labels"], custom_id)
- return {"request": vertex_request_body}
+ return ({"request": vertex_request_body},)
- def _iter_stripped_lines(raw_lines: Iterable[Union[str, bytes]]) -> Iterator[str]:
+ def _iter_stripped_lines(raw_lines: Iterable[str | bytes]) -> Iterator[str]:
"""Decode (when needed), strip, and drop blank lines from an iterable of lines."""
for raw in raw_lines:
line = raw.decode("utf-8") if isinstance(raw, (bytes, bytearray)) else raw
@@@ -1099,13 -797,24 +1091,13 @@@ class VertexAIFilesConfig(VertexBase, B
response_dict = transformed_response.model_dump()
# Return in OpenAI batch format
- return {
- "id": f"batch_req_{uuid.uuid4()}",
- "custom_id": custom_id,
- "response": {
- "status_code": 200,
- "request_id": response_dict.get("id", ""),
- "body": response_dict,
- },
- "error": None,
- }
+ return _openai_batch_output_row(custom_id=custom_id, body=response_dict)
except Exception as e:
- return {
- "id": f"batch_req_{uuid.uuid4()}",
- "custom_id": custom_id,
- "response": None,
- "error": {
+ return _openai_batch_output_row(
+ custom_id=custom_id,
+ error={
"code": "transformation_error",
- "message": f"Failed to transform response: {str(e)}",
+ "message": f"Failed to transform response: {e!s}",
},
- }
+ )