Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
f6d5502
feat(vertex-ai): transform batch prediction outputs to OpenAI format
Sameerlite Apr 13, 2026
380c14e
fix: address Greptile review comments
Sameerlite Apr 13, 2026
19c54b6
Fix code qa
Sameerlite Apr 14, 2026
f6c7e4e
Fix greptile review
Sameerlite Apr 14, 2026
e3eb1b5
Fix greptile review
Sameerlite Apr 14, 2026
2f4b7bc
Merge pull request #25944 from BerriAI/litellm_internal_staging
Sameerlite Apr 17, 2026
cc1100b
Merge pull request #26305 from BerriAI/litellm_internal_staging
Sameerlite Apr 23, 2026
493405c
Fix lint
Sameerlite May 1, 2026
8b85deb
Merge pull request #26985 from BerriAI/litellm_internal_staging
Sameerlite May 1, 2026
7deac91
Fix Vertex batch custom id labels
cursoragent May 1, 2026
0cbb35c
Fix Vertex batch output transformation detection
cursoragent May 1, 2026
60ca442
Fix Vertex batch output edge cases
cursoragent May 1, 2026
8914457
Fix code qa
Sameerlite May 2, 2026
9275eea
Address bugbot: drop dead encode/decode helpers; preserve empty custo…
cursoragent May 2, 2026
9d51706
Merge remote-tracking branch 'origin/litellm_internal_staging' into l…
cursoragent May 2, 2026
10261e4
Forward Vertex file content logging context
cursoragent May 2, 2026
12ecac6
test vertex file content logging forwarding
cursoragent May 2, 2026
04133ba
Fix Vertex batch output logging mutation
cursoragent May 2, 2026
480bea2
fix: don't mutate caller's logging_obj in _try_transform_vertex_batch…
cursoragent May 2, 2026
4392175
feat: add opt-out flag for Vertex batch output transformation
mateo-berri May 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions litellm/llms/vertex_ai/files/handler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import time
import urllib.parse
from typing import Any, Coroutine, Optional, Tuple, Union

Expand All @@ -16,9 +17,10 @@
HttpxBinaryResponseContent,
OpenAIFileObject,
)
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES

from .transformation import VertexAIJsonlFilesTransformation
from .transformation import VertexAIFilesConfig, VertexAIJsonlFilesTransformation

vertex_ai_files_transformation = VertexAIJsonlFilesTransformation()

Expand Down Expand Up @@ -188,11 +190,32 @@ async def afile_content(
mock_response = httpx.Response(
status_code=200,
content=file_content,
headers={"content-type": "application/octet-stream"},
headers={
"content-type": "application/octet-stream",
"content-length": str(len(file_content)),
},
request=httpx.Request(method="GET", url=decoded_path),
)

return HttpxBinaryResponseContent(response=mock_response)
# Apply transformation to convert Vertex AI batch outputs to OpenAI format
config = VertexAIFilesConfig()

# Create a logging object for transformation
logging_obj = Logging(
model="",
messages=[],
stream=False,
call_type="afile_content",
start_time=time.time(),
litellm_call_id="",
function_id="",
)
Comment thread
Sameerlite marked this conversation as resolved.
Resolved

return config.transform_file_content_response(
raw_response=mock_response,
logging_obj=logging_obj,
litellm_params={}
)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

def file_content(
self,
Expand Down
276 changes: 275 additions & 1 deletion litellm/llms/vertex_ai/files/transformation.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import json
import os
import re
import time
from typing import Any, Dict, List, Optional, Tuple, Union

import httpx
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
from httpx import Headers, Response
from openai.types.file_deleted import FileDeleted

from litellm._uuid import uuid
from litellm.files.utils import FilesAPIUtils
from litellm.litellm_core_utils.litellm_logging import Logging
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
Sameerlite marked this conversation as resolved.
Dismissed
from litellm.litellm_core_utils.prompt_templates.common_utils import extract_file_data
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.base_llm.files.transformation import (
Expand All @@ -31,12 +34,31 @@
PathLike,
)
from litellm.types.llms.vertex_ai import GcsBucketResponse
from litellm.types.utils import ExtractedFileData, LlmProviders
from litellm.types.utils import ExtractedFileData, LlmProviders, ModelResponse
Comment thread
Sameerlite marked this conversation as resolved.
Dismissed

from ..common_utils import VertexAIError
from ..vertex_llm_base import VertexBase


def _sanitize_gcp_label_value(value: str) -> str:
"""
Sanitize a string to meet GCP label value constraints.

GCP label values must:
- Be lowercase
- Contain only letters, numbers, underscores, and hyphens
- Be max 63 characters

Args:
value: The string to sanitize

Returns:
A sanitized string that meets GCP label constraints
"""
sanitized = re.sub(r"[^a-z0-9_-]", "_", value.lower())
return sanitized[:63]


class VertexAIFilesConfig(VertexBase, BaseFilesConfig):
"""
Config for VertexAI Files
Expand Down Expand Up @@ -247,6 +269,14 @@
litellm_params={},
cached_content=None,
)

# Add custom_id as a label for correlation in batch outputs
custom_id = _openai_jsonl_content.get("custom_id")
if custom_id:
if "labels" not in vertex_request_body:
vertex_request_body["labels"] = {}
vertex_request_body["labels"]["litellm_custom_id"] = _sanitize_gcp_label_value(str(custom_id))

vertex_jsonl_content.append({"request": vertex_request_body})
return vertex_jsonl_content

Expand Down Expand Up @@ -453,7 +483,243 @@
logging_obj: LiteLLMLoggingObj,
litellm_params: dict,
) -> HttpxBinaryResponseContent:
"""
Transform file content response, converting Vertex AI batch output to OpenAI format if applicable.

This method automatically detects and transforms Vertex AI batch prediction outputs
(predictions.jsonl files) into OpenAI-compatible batch response format.

If the file is not a batch output or transformation fails, the original content
is returned as-is to maintain backward compatibility.
"""
try:
# Try to transform batch output if it's a JSONL file
content = raw_response.content
if content:
transformed_content = self._try_transform_vertex_batch_output_to_openai(
content
)
if transformed_content != content:
# Create a new response with transformed content and updated Content-Length
import httpx

# Update headers with correct Content-Length
new_headers = dict(raw_response.headers)
new_headers["content-length"] = str(len(transformed_content))

mock_response = httpx.Response(
status_code=raw_response.status_code,
content=transformed_content,
headers=new_headers,
request=raw_response.request,
)
return HttpxBinaryResponseContent(response=mock_response)
except Exception:
# If transformation fails, return as-is
pass

return HttpxBinaryResponseContent(response=raw_response)

def _try_transform_vertex_batch_output_to_openai(
self, content: bytes
) -> bytes:
"""
Try to transform Vertex AI batch output to OpenAI format.
If conversion fails at any point, return the original content as-is.

Vertex AI batch output format (predictions.jsonl):
{
"request": {"contents": [...], "labels": {"litellm_custom_id": "request-1"}},
"status": "",
"response": {"candidates": [...], "modelVersion": "gemini-2.5-flash", ...},
"processed_time": "2026-04-13T10:18:18.102004+00:00"
}

OpenAI batch output format:
{
"id": "batch_req_...",
"custom_id": "request-1",
"response": {
"status_code": 200,
"request_id": "chatcmpl-...",
"body": {<OpenAI chat completion response>}
},
"error": null
}
"""
try:
# Decode content
content_str = content.decode("utf-8")

# Check if it's JSONL (multiple lines)
lines = content_str.strip().split("\n")
if not lines:
return content

# Try to parse the first line to see if it's Vertex AI batch output
first_line = json.loads(lines[0])

# Check if it has Vertex AI batch output structure with discriminating fields
# Must have request, response, and processed_time
# Plus either candidates (success) or status (error)
has_base_structure = (
"response" in first_line
and "request" in first_line
and "processed_time" in first_line
)
has_success_or_error = (
"candidates" in first_line.get("response", {})
or "status" in first_line
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

if not (has_base_structure and has_success_or_error):
# Not a Vertex AI batch output, return as-is
return content
Comment thread
Sameerlite marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

# Transform all lines
transformed_lines = []
for line in lines:
if not line.strip():
continue

try:
vertex_output = json.loads(line)
openai_output = self._transform_single_vertex_batch_output_to_openai(
vertex_output
)
transformed_lines.append(json.dumps(openai_output))
except Exception:
# If any line fails, return original content
return content

# Return transformed content
return "\n".join(transformed_lines).encode("utf-8")

except Exception:
# If anything fails, return original content
return content

def _transform_single_vertex_batch_output_to_openai(
self, vertex_output: Dict[str, Any]
) -> Dict[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
custom_id = "unknown"
request_data = vertex_output.get("request", {})
labels = request_data.get("labels", {})
if "litellm_custom_id" in labels:
custom_id = labels["litellm_custom_id"]
Comment thread
Sameerlite marked this conversation as resolved.
Resolved

# Check if there's an error
status = vertex_output.get("status", "")
has_error = bool(status)

if has_error:
# Return error response in OpenAI format
return {
"id": f"batch_req_{uuid.uuid4()}",
"custom_id": custom_id,
"response": {
"status_code": 400,
"request_id": "",
"body": {
"error": {
"message": status,
"type": "vertex_ai_error",
"code": "vertex_ai_error"
}
}
},
"error": {
"message": status,
"type": "vertex_ai_error",
"code": "vertex_ai_error"
}
}

# Transform successful response using existing transformation
vertex_response = vertex_output.get("response", {})

# Extract model from response
model = vertex_response.get("modelVersion", "gemini-1.5-flash-001")
if "@" in model:
model = model.split("@")[0]

# Create logging object for transformation
from litellm.litellm_core_utils.litellm_logging import Logging

logging_obj = Logging(
model=model,
messages=[],
stream=False,
call_type="batch_transform",
start_time=time.time(),
litellm_call_id="",
function_id="",
)
logging_obj.optional_params = {}

# Create mock httpx response for transformation
mock_httpx_response = httpx.Response(
status_code=200,
content=json.dumps(vertex_response).encode("utf-8"),
headers={"content-type": "application/json"},
request=httpx.Request(method="POST", url="https://example.com"),
)

try:
# Use existing VertexGeminiConfig transformation
vertex_gemini_config = VertexGeminiConfig()
model_response = ModelResponse()
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

transformed_response = vertex_gemini_config._transform_google_generate_content_to_openai_model_response(
completion_response=vertex_response,
model_response=model_response,
model=model,
logging_obj=logging_obj,
raw_response=mock_httpx_response,
)

# Convert ModelResponse to dict
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
}

except Exception as e:
# If transformation fails, return error
return {
"id": f"batch_req_{uuid.uuid4()}",
"custom_id": custom_id,
"response": {
"status_code": 500,
"request_id": "",
"body": {
"error": {
"message": f"Failed to transform response: {str(e)}",
"type": "transformation_error",
"code": "transformation_error"
}
}
},
"error": {
"message": f"Failed to transform response: {str(e)}",
"type": "transformation_error",
"code": "transformation_error"
}
}


class VertexAIJsonlFilesTransformation(VertexGeminiConfig):
Expand Down Expand Up @@ -513,6 +779,14 @@
litellm_params={},
cached_content=None,
)

# Add custom_id as a label for correlation in batch outputs
custom_id = _openai_jsonl_content.get("custom_id")
if custom_id:
if "labels" not in vertex_request_body:
vertex_request_body["labels"] = {}
vertex_request_body["labels"]["litellm_custom_id"] = _sanitize_gcp_label_value(str(custom_id))

vertex_jsonl_content.append({"request": vertex_request_body})
return vertex_jsonl_content

Expand Down
Loading
Loading