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

milan8f1f738b1d7f
diff --cc litellm/llms/vertex_ai/files/transformation.py
index 88acd7768c2,eb0bc719596..a52e47713ec
--- a/litellm/llms/vertex_ai/files/transformation.py
+++ b/litellm/llms/vertex_ai/files/transformation.py
@@@ -5,11 -5,8 +5,9 @@@ import jso
import os
import re
import time
-from collections.abc import Callable, Iterable, Iterator
+from collections.abc import Callable, Iterable, Iterator, Mapping
- from typing import (
- Any,
- )
+ from typing import Any, Final
+from urllib.parse import quote, unquote
import httpx
from httpx import Headers, Response
@@@ -70,16 -58,8 +68,16 @@@ from litellm.types.utils import
from ..common_utils import VertexAIError
from ..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_REQUEST_FIELD_BY_GEMINI_PARAM = (
+ _GCP_LABEL_VALUE_MAX_LEN: Final = 63
+ _CUSTOM_ID_RAW_LABEL_PREFIX: Final = "b32_"
++_VERTEX_BATCH_KEY_FIELD: Final = "key"
++_MANAGED_GCS_MODEL_PATH_PATTERN: Final = re.compile(r"publishers/[^/]+/models/([^/?]+)")
++_EMBED_REQUEST_FIELD_BY_GEMINI_PARAM: Final = (
+ ("outputDimensionality", "output_dimensionality"),
+ ("taskType", "task_type"),
+ ("title", "title"),
+)
- _VERTEX_BATCH_FANNED_OUT_KEY_PATTERN = re.compile(r"(?P<custom_id>[^#]*)#(?P<index>\d+)/(?P<total>\d+)")
++_VERTEX_BATCH_FANNED_OUT_KEY_PATTERN: Final = re.compile(r"(?P<custom_id>[^#]*)#(?P<index>\d+)/(?P<total>\d+)")
def _sanitize_gcp_label_value(value: str) -> str:
@@@ -142,31 -122,13 +140,31 @@@ def _set_litellm_batch_custom_id_labels
labels[f"litellm_custom_id_raw_{index}"] = raw_label_chunk
-def _get_litellm_batch_custom_id_from_labels(labels: dict[str, Any]) -> str:
+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")
+ labels = request_data.get("labels") if isinstance(request_data, Mapping) else None
+ return _get_litellm_batch_custom_id_from_labels(labels)
+
+
+def _get_litellm_batch_custom_id_from_labels(labels: Mapping[str, Any] | None) -> str:
"""Prefer encoded custom_id when present (see _set_litellm_batch_custom_id_labels)."""
+ if not labels:
+ return "unknown"
- raw = labels.get("litellm_custom_id_raw")
+ raw: Final = labels.get("litellm_custom_id_raw")
if raw:
- raw_chunks = [str(raw)]
- chunk_prefix = "litellm_custom_id_raw_"
- indexed_chunks = []
+ raw_chunks: Final = [str(raw)]
+ chunk_prefix: Final = "litellm_custom_id_raw_"
+ indexed_chunks: Final = []
for key, value in labels.items():
if key.startswith(chunk_prefix) and key[len(chunk_prefix) :].isdigit():
indexed_chunks.append((int(key[len(chunk_prefix) :]), str(value)))
@@@ -461,11 -151,8 +459,11 @@@ def _openai_batch_jsonl_entry_to_vertex
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_rows(openai_entry)
+
- openai_request_body = openai_entry.get("body") or {}
- vertex_request_body = _transform_request_body(
+ openai_request_body: Final = openai_entry.get("body") or {}
+ vertex_request_body: Final = _transform_request_body(
messages=openai_request_body.get("messages", []),
model=openai_request_body.get("model", ""),
optional_params=map_openai_to_vertex_params(openai_request_body),
@@@ -928,12 -615,11 +926,12 @@@ class VertexAIFilesConfig(VertexBase, B
return HttpxBinaryResponseContent(response=raw_response)
# Try to transform batch output if it's a JSONL file
- content = raw_response.content
+ content: Final = raw_response.content
if content:
- transformed_content = self._try_transform_vertex_batch_output_to_openai(
+ transformed_content: Final = 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
@@@ -999,8 -682,8 +997,8 @@@
# discriminating fields. Anything else (e.g. a binary file whose
# 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_embeddings_batch_output_row(first_row) or (
+ first_row: Final = json.loads(first_line)
- is_vertex_batch_output: Final = (
++ is_vertex_batch_output: Final = _is_vertex_embeddings_batch_output_row(first_row) or (
"request" in first_row
and "response" in first_row
and "processed_time" in first_row
@@@ -1080,21 -751,28 +1078,21 @@@
Transform a single Vertex AI batch output line to OpenAI format.
Uses the existing VertexGeminiConfig transformation for the response.
"""
- custom_id = _get_litellm_batch_custom_id(vertex_output)
- # Extract custom_id from request labels (prefer raw for OpenAI round-trip)
- request_data: Final = vertex_output.get("request", {})
- labels: Final = request_data.get("labels", {}) or {}
- custom_id: Final = _get_litellm_batch_custom_id_from_labels(labels)
++ custom_id: Final = _get_litellm_batch_custom_id(vertex_output)
# Check if there's an error
- status = vertex_output.get("status", "")
- has_error = bool(status)
+ status: Final = vertex_output.get("status", "")
+ has_error: Final = 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",
+ error_message=status,
+ )
# Transform successful response using existing transformation
- vertex_response = vertex_output.get("response", {})
+ vertex_response: Final = vertex_output.get("response", {})
# Extract model from response
model = vertex_response.get("modelVersion", "gemini-1.5-flash-001")
@@@ -1114,14 -792,27 +1112,14 @@@
)
# Convert ModelResponse to dict
- response_dict = transformed_response.model_dump()
+ response_dict: Final = 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": {
- "code": "transformation_error",
- "message": f"Failed to transform response: {e}",
- },
- }
+ return _openai_batch_output_row(
+ custom_id=custom_id,
+ error_code="transformation_error",
+ error_message=f"Failed to transform response: {e}",
+ )