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
fix(vertex_ai): translate /v1/embeddings batch rows to Gemini embedding shape
milan6cfcb6cd839c
diff --git a/litellm/llms/vertex_ai/files/transformation.py b/litellm/llms/vertex_ai/files/transformation.pyindex dd877b52eb8..516a3ca7184 100644--- a/litellm/llms/vertex_ai/files/transformation.py+++ b/litellm/llms/vertex_ai/files/transformation.py@@ -5,6 +5,7 @@ import jsonimport osimport reimport time+from collections.abc import Mappingfrom typing import (Any,Callable,@@ -16,6 +17,7 @@ from typing import (Tuple,Union,)+from urllib.parse import unquoteimport httpxfrom httpx import Headers, Response@@ -51,6 +53,9 @@ from litellm.llms.vertex_ai.gemini.transformation import _transform_request_bodyfrom 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.llms.openai import (AllMessageValues,CreateFileRequest,@@ -62,13 +67,26 @@ from litellm.types.llms.openai import ()from litellm.types.files import StreamingMediaUploadConfigfrom litellm.types.llms.vertex_ai import GcsBucketResponse-from litellm.types.utils import LlmProviders, ModelResponse+from litellm.types.utils import (+ Embedding,+ EmbeddingResponse,+ LlmProviders,+ ModelResponse,+ Usage,+)from ..common_utils import VertexAIErrorfrom ..vertex_llm_base import VertexBase_GCP_LABEL_VALUE_MAX_LEN = 63_CUSTOM_ID_RAW_LABEL_PREFIX = "b32_"+_VERTEX_BATCH_KEY_FIELD = "key"+_MANAGED_GCS_MODEL_PATH_PATTERN = re.compile(r"publishers/[^/]+/models/([^/?]+)")+_EMBED_CONTENT_CONFIG_FIELD_BY_GEMINI_PARAM = {+ "outputDimensionality": "output_dimensionality",+ "taskType": "task_type",+ "title": "title",+}def _sanitize_gcp_label_value(value: str) -> str:@@ -131,6 +149,21 @@ def _set_litellm_batch_custom_id_labels(labels: Dict[str, str], custom_id: Any)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 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:"""Prefer encoded custom_id when present (see _set_litellm_batch_custom_id_labels)."""raw = labels.get("litellm_custom_id_raw")@@ -149,10 +182,156 @@ def _get_litellm_batch_custom_id_from_labels(labels: Dict[str, Any]) -> str:return str(labels.get("litellm_custom_id", "unknown"))+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 _transform_vertex_embeddings_batch_output_row_to_openai(+ vertex_output_row: Mapping[str, Any],+ model: str | None,+) -> Mapping[str, Any]:+ """+ Transforms one Vertex Gemini Embedding batch output row into an OpenAI batch+ output row holding an `/v1/embeddings` response body.++ Example Vertex jsonl+ {"key": "id_1", "request": {...}, "response": {"tokenCount": "2", "embedding": {"values": [-0.015, 0.024]}}}++ `tokenCount` is serialized as a string by Vertex (int64 proto field), and the row+ carries no `modelVersion`, so the model comes from the batch the row belongs to.+ """+ custom_id = _get_litellm_batch_custom_id(vertex_output_row)+ status = vertex_output_row.get("status", "")+ if status:+ return _openai_batch_output_row(+ custom_id=custom_id,+ error={"code": "vertex_ai_error", "message": status},+ )++ vertex_response = vertex_output_row.get("response") or {}+ token_count = int(vertex_response.get("tokenCount") or 0)+ body = EmbeddingResponse(+ model=model or "",+ data=[+ Embedding(+ embedding=vertex_response["embedding"]["values"],+ index=0,+ object="embedding",+ )+ ],+ usage=Usage(prompt_tokens=token_count, total_tokens=token_count),+ ).model_dump()+ return _openai_batch_output_row(custom_id=custom_id, body=body)+++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_batch_jsonl_entry_to_vertex_embeddings_row(+ openai_entry: Mapping[str, Any],+) -> Mapping[str, Any]:+ """+ Transforms a single OpenAI `/v1/embeddings` batch entry into a Vertex Gemini+ Embedding batch row.++ Example Vertex jsonl+ {"key": "id_1", "request": {"content": {"parts": [{"text": "Hello World"}]}}, "embed_content_config": {"output_dimensionality": 768, "task_type": "RETRIEVAL_DOCUMENT"}}++ Note that `content` is singular (an `EmbedContentRequest`, not a+ `GenerateContentRequest`), the per-row config is a sibling of `request` rather than+ part of it, and the `custom_id` round-trips through the top-level `key`.++ 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")++ embed_content_request = transform_openai_input_gemini_embed_content(+ input=embedding_input,+ model=openai_request_body.get("model", ""),+ optional_params=openai_request_body,+ )+ embed_content_config = {+ config_field: embed_content_request[gemini_param]+ for gemini_param, config_field in _EMBED_CONTENT_CONFIG_FIELD_BY_GEMINI_PARAM.items()+ if gemini_param in embed_content_request+ }++ custom_id = openai_entry.get("custom_id")+ return {+ **({_VERTEX_BATCH_KEY_FIELD: str(custom_id)} if custom_id is not None else {}),+ "request": {"content": embed_content_request["content"]},+ **({"embed_content_config": embed_content_config} if embed_content_config else {}),+ }++def _openai_batch_jsonl_entry_to_vertex_wrapped_request(openai_entry: Dict[str, Any],map_openai_to_vertex_params: Callable[[Dict[str, Any]], Dict[str, Any]],-) -> Dict[str, Any]:+) -> Mapping[str, Any]:"""Transforms a single OpenAI JSONL batch entry into its Vertex wrapped request.@@ -160,6 +339,9 @@ def _openai_batch_jsonl_entry_to_vertex_wrapped_request(Example Vertex jsonl{"request":{"contents": [{"role": "user", "parts": [{"text": "What is the relation between the following video and image samples?"}, {"fileData": {"fileUri": "gs://cloud-samples-data/generative-ai/video/animals.mp4", "mimeType": "video/mp4"}}, {"fileData": {"fileUri": "gs://cloud-samples-data/generative-ai/image/cricket.jpeg", "mimeType": "image/jpeg"}}]}]}}"""+ if _is_embeddings_batch_entry(openai_entry):+ return _openai_batch_jsonl_entry_to_vertex_embeddings_row(openai_entry)+openai_request_body = openai_entry.get("body") or {}vertex_request_body = _transform_request_body(messages=openai_request_body.get("messages", []),@@ -629,6 +811,7 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):transformed_content = self._try_transform_vertex_batch_output_to_openai(content=content,logging_obj=logging_obj,+ model=_model_from_managed_gcs_url(str(raw_response.request.url)),)if transformed_content != content:# Create a new response with transformed content and updated Content-Length@@ -650,7 +833,10 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):return HttpxBinaryResponseContent(response=raw_response)def _try_transform_vertex_batch_output_to_openai(- self, content: bytes, logging_obj: Optional[LiteLLMLoggingObj] = None+ self,+ content: bytes,+ logging_obj: LiteLLMLoggingObj | None = None,+ model: str | None = None,) -> bytes:"""Try to transform Vertex AI batch output to OpenAI format.@@ -692,7 +878,7 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):# first line is not valid UTF-8/JSON) raises and falls through to the# passthrough below, leaving the content untouched.first_row = json.loads(first_line)- is_vertex_batch_output = (+ is_vertex_batch_output = _is_vertex_embeddings_batch_output_row(first_row) or ("request" in first_rowand "response" in first_rowand "processed_time" in first_row@@ -731,11 +917,19 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):output = bytearray()for line in itertools.chain([first_line], lines):try:- openai_output = self._transform_single_vertex_batch_output_to_openai(- vertex_output=json.loads(line),- vertex_gemini_config=vertex_gemini_config,- logging_obj=batch_transform_logging_obj,- mock_httpx_response=mock_httpx_response,+ vertex_output_row = json.loads(line)+ openai_output = (+ _transform_vertex_embeddings_batch_output_row_to_openai(+ vertex_output_row=vertex_output_row,+ model=model,+ )+ if _is_vertex_embeddings_batch_output_row(vertex_output_row)+ else self._transform_single_vertex_batch_output_to_openai(+ vertex_output=vertex_output_row,+ vertex_gemini_config=vertex_gemini_config,+ logging_obj=batch_transform_logging_obj,+ mock_httpx_response=mock_httpx_response,+ ))except Exception:return content@@ -755,30 +949,22 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):vertex_gemini_config: VertexGeminiConfig,logging_obj: Logging,mock_httpx_response: httpx.Response,- ) -> Dict[str, Any]:+ ) -> Mapping[str, Any]:"""Transform a single Vertex AI batch output line to OpenAI format.Uses the existing VertexGeminiConfig transformation for the response."""- # Extract custom_id from request labels (prefer raw for OpenAI round-trip)- request_data = vertex_output.get("request", {})- labels = request_data.get("labels", {}) or {}- custom_id = _get_litellm_batch_custom_id_from_labels(labels)+ custom_id = _get_litellm_batch_custom_id(vertex_output)# Check if there's an errorstatus = vertex_output.get("status", "")has_error = bool(status)if has_error:- return {- "id": f"batch_req_{uuid.uuid4()}",- "custom_id": custom_id,- "response": None,- "error": {- "code": "vertex_ai_error",- "message": status,- },- }+ return _openai_batch_output_row(+ custom_id=custom_id,+ error={"code": "vertex_ai_error", "message": status},+ )# Transform successful response using existing transformationvertex_response = vertex_output.get("response", {})@@ -804,24 +990,13 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):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)}",},- }+ )diff --git a/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.py b/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.pyindex 8c5305ee67b..636a3106617 100644--- a/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.py+++ b/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.py@@ -1318,3 +1318,280 @@ class TestConfiguredBucketNameResolution:assert "bucket_name" in OPTIONAL_KWARGS_KEYSparams = get_litellm_params(bucket_name="my-legacy-bucket")assert params.get("bucket_name") == "my-legacy-bucket"+++def _embeddings_entry(**overrides):+ entry = {+ "custom_id": "request-1",+ "method": "POST",+ "url": "/v1/embeddings",+ "body": {"model": "gemini-embedding-2", "input": "hello world"},+ }+ entry.update(overrides)+ return entry+++class TestVertexEmbeddingsBatchInputTranslation:+ """+ /v1/embeddings batch lines must be translated to Vertex's Gemini Embedding batch+ shape, not the generateContent shape.++ Ref: https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/batch-prediction-genai-embeddings+ """++ def test_should_emit_embed_content_request_shape(self):+ (row,) = _wrap_entries([_embeddings_entry()])++ assert row["request"] == {"content": {"parts": [{"text": "hello world"}]}}+ assert "contents" not in row["request"]+ assert "labels" not in row["request"]++ def test_should_round_trip_custom_id_through_top_level_key(self):+ (row,) = _wrap_entries([_embeddings_entry(custom_id="MyRequest-1")])++ assert row["key"] == "MyRequest-1"++ def test_should_omit_key_when_no_custom_id(self):+ entry = _embeddings_entry()+ del entry["custom_id"]++ (row,) = _wrap_entries([entry])++ assert "key" not in row++ def test_should_map_openai_params_to_embed_content_config_sibling(self):+ (row,) = _wrap_entries(+ [+ _embeddings_entry(+ body={+ "model": "gemini-embedding-001",+ "input": "hello world",+ "dimensions": 768,+ "task_type": "RETRIEVAL_DOCUMENT",+ "title": "some_title",+ }+ )+ ]+ )++ assert row["embed_content_config"] == {+ "output_dimensionality": 768,+ "task_type": "RETRIEVAL_DOCUMENT",+ "title": "some_title",+ }+ assert "output_dimensionality" not in row["request"]++ def test_should_omit_embed_content_config_when_no_params_given(self):+ (row,) = _wrap_entries([_embeddings_entry()])++ assert "embed_content_config" not in row++ def test_should_translate_multimodal_gcs_input(self):+ (row,) = _wrap_entries(+ [+ _embeddings_entry(+ body={+ "model": "gemini-embedding-2",+ "input": "gs://cloud-samples-data/generative-ai/image/benchmark.jpeg",+ }+ )+ ]+ )++ assert row["request"]["content"]["parts"] == [+ {+ "file_data": {+ "mime_type": "image/jpeg",+ "file_uri": "gs://cloud-samples-data/generative-ai/image/benchmark.jpeg",+ }+ }+ ]++ @pytest.mark.parametrize("url", ["/v1/embeddings", "v1/embeddings", "/v1/embeddings/"])+ def test_should_detect_embeddings_route_variants(self, url):+ (row,) = _wrap_entries([_embeddings_entry(url=url)])++ assert "content" in row["request"]++ def test_should_raise_when_input_missing(self):+ with pytest.raises(ValueError, match="`input` is required"):+ _wrap_entries([_embeddings_entry(body={"model": "gemini-embedding-2"})])++ def test_should_keep_chat_completions_lines_on_generate_content_path(self):+ (row,) = _wrap_entries(+ [+ {+ "custom_id": "request-1",+ "method": "POST",+ "url": "/v1/chat/completions",+ "body": {+ "model": "gemini-2.0-flash-001",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ }+ ]+ )++ assert row["request"]["contents"] == [+ {"role": "user", "parts": [{"text": "Hello"}]}+ ]+ assert row["request"]["labels"]["litellm_custom_id"] == "request-1"+ assert "key" not in row++ def test_should_translate_each_line_by_its_own_url(self):+ chat_row, embeddings_row = _wrap_entries(+ [+ {+ "custom_id": "chat-1",+ "url": "/v1/chat/completions",+ "body": {+ "model": "gemini-2.0-flash-001",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ },+ _embeddings_entry(custom_id="embed-1"),+ ]+ )++ assert "contents" in chat_row["request"]+ assert "content" in embeddings_row["request"]+++class TestVertexEmbeddingsBatchOutputTranslation:+ """Vertex Gemini Embedding batch output rows must come back as OpenAI batch rows."""++ def _vertex_embeddings_output_row(self, **overrides):+ row = {+ "key": "request-1",+ "request": {"content": {"parts": [{"text": "hello world"}]}},+ "response": {+ "tokenCount": "2",+ "embedding": {"values": [-0.015, 0.024]},+ },+ }+ row.update(overrides)+ return row++ def _transform(self, config, rows, url="https://example.com"):+ content = "\n".join(json.dumps(row) for row in rows).encode("utf-8")+ result = config.transform_file_content_response(+ raw_response=httpx.Response(+ status_code=200,+ content=content,+ headers={"content-type": "application/octet-stream"},+ request=httpx.Request("GET", url),+ ),+ logging_obj=MagicMock(),+ litellm_params={},+ )+ return [+ json.loads(line)+ for line in result.response.content.decode("utf-8").split("\n")+ ]++ def test_should_transform_embeddings_output_to_openai_batch_row(self, config):+ (result,) = self._transform(config, [self._vertex_embeddings_output_row()])++ assert result["custom_id"] == "request-1"+ assert result["error"] is None+ assert result["response"]["status_code"] == 200+ body = result["response"]["body"]+ assert body["object"] == "list"+ assert body["data"] == [+ {"embedding": [-0.015, 0.024], "index": 0, "object": "embedding"}+ ]+ assert body["usage"]["prompt_tokens"] == 2+ assert body["usage"]["total_tokens"] == 2++ def test_should_resolve_model_from_managed_gcs_object_path(self, config):+ object_path = urllib.parse.quote(+ "litellm-vertex-files/publishers/google/models/gemini-embedding-2/"+ "prediction-model-2026-07-29T05:55:52Z/predictions.jsonl",+ safe="",+ )+ url = f"https://storage.googleapis.com/storage/v1/b/my-bucket/o/{object_path}?alt=media"++ (result,) = self._transform(+ config, [self._vertex_embeddings_output_row()], url=url+ )++ assert result["response"]["body"]["model"] == "gemini-embedding-2"++ def test_should_surface_failed_embeddings_row_as_error(self, config):+ (result,) = self._transform(+ config,+ [+ self._vertex_embeddings_output_row(+ status="Failed to parse JSON into proto", response={}+ )+ ],+ )++ assert result["custom_id"] == "request-1"+ assert result["response"] is None+ assert result["error"]["code"] == "vertex_ai_error"+ assert "Failed to parse JSON into proto" in result["error"]["message"]++ def test_should_transform_every_row_of_a_multi_row_file(self, config):+ results = self._transform(+ config,+ [+ self._vertex_embeddings_output_row(key=f"request-{index}")+ for index in range(3)+ ],+ )++ assert [result["custom_id"] for result in results] == [+ "request-0",+ "request-1",+ "request-2",+ ]++ def test_should_end_to_end_round_trip_openai_embeddings_batch(self, config):+ (vertex_row,) = _wrap_entries(+ [+ _embeddings_entry(+ custom_id="MyRequest-1",+ body={+ "model": "gemini-embedding-2",+ "input": "hello world",+ "dimensions": 2,+ },+ )+ ]+ )++ (result,) = self._transform(+ config,+ [+ {+ **vertex_row,+ "status": "",+ "processed_time": "2026-07-29T05:55:52.379528Z",+ "response": {+ "tokenCount": "2",+ "embedding": {"values": [-0.015, 0.024]},+ },+ }+ ],+ )++ assert result["custom_id"] == "MyRequest-1"+ assert result["response"]["body"]["data"][0]["embedding"] == [-0.015, 0.024]++ def test_should_leave_legacy_predict_embeddings_output_untouched(self, config):+ legacy_row = {+ "instance": {"content": "hello world"},+ "predictions": [+ {+ "embeddings": {+ "statistics": {"token_count": 2, "truncated": False},+ "values": [0.2],+ }+ }+ ],+ "status": "",+ }+ content = json.dumps(legacy_row).encode("utf-8")++ assert config._try_transform_vertex_batch_output_to_openai(content) == content