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): surface real error/status on vertex batch create instead of IndexError 500
Devin AIb93030f84e7a
diff --git a/litellm/llms/vertex_ai/batches/handler.py b/litellm/llms/vertex_ai/batches/handler.pyindex ada1356fb6b..f0fd5480c75 100644--- a/litellm/llms/vertex_ai/batches/handler.py+++ b/litellm/llms/vertex_ai/batches/handler.py@@ -13,7 +13,7 @@ from litellm.llms.custom_httpx.http_handler import (_get_httpx_client,get_async_httpx_client,)-from litellm.llms.vertex_ai.common_utils import get_vertex_base_url+from litellm.llms.vertex_ai.common_utils import VertexAIError, get_vertex_base_urlfrom litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexLLMfrom litellm.types.llms.openai import CreateBatchRequestfrom litellm.types.llms.vertex_ai import (@@ -98,7 +98,9 @@ class VertexAIBatchPrediction(VertexLLM):)if response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )_json_response = response.json()vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(@@ -130,7 +132,9 @@ class VertexAIBatchPrediction(VertexLLM):)raiseif response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )_json_response = response.json()vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(@@ -242,7 +246,9 @@ class VertexAIBatchPrediction(VertexLLM):)if response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )_json_response = response.json()vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(@@ -292,7 +298,9 @@ class VertexAIBatchPrediction(VertexLLM):headers=headers,)if response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )_json_response = response.json()vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(@@ -365,7 +373,9 @@ class VertexAIBatchPrediction(VertexLLM):)if response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )_json_response = response.json()vertex_batch_response = (@@ -390,7 +400,9 @@ class VertexAIBatchPrediction(VertexLLM):params=params,)if response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )_json_response = response.json()vertex_batch_response = (@@ -475,7 +487,9 @@ class VertexAIBatchPrediction(VertexLLM):raiseif response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )# HTTPHandler.get() does not accept a timeout parameterretrieve_response = sync_handler.get(@@ -488,7 +502,10 @@ class VertexAIBatchPrediction(VertexLLM):retrieve_response.status_code,retrieve_response.text[:1000],)- raise Exception(f"Error: {retrieve_response.status_code} {retrieve_response.text}")+ raise VertexAIError(+ status_code=retrieve_response.status_code,+ message=f"Error: {retrieve_response.status_code} {retrieve_response.text}",+ )_json_response = retrieve_response.json()vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(@@ -521,7 +538,9 @@ class VertexAIBatchPrediction(VertexLLM):)raiseif response.status_code != 200:- raise Exception(f"Error: {response.status_code} {response.text}")+ raise VertexAIError(+ status_code=response.status_code, message=f"Error: {response.status_code} {response.text}"+ )# AsyncHTTPHandler.get() does not accept a timeout parameterretrieve_response = await client.get(@@ -534,7 +553,10 @@ class VertexAIBatchPrediction(VertexLLM):retrieve_response.status_code,retrieve_response.text[:1000],)- raise Exception(f"Error: {retrieve_response.status_code} {retrieve_response.text}")+ raise VertexAIError(+ status_code=retrieve_response.status_code,+ message=f"Error: {retrieve_response.status_code} {retrieve_response.text}",+ )_json_response = retrieve_response.json()vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(diff --git a/litellm/llms/vertex_ai/batches/transformation.py b/litellm/llms/vertex_ai/batches/transformation.pyindex df903ba7ef0..e4299bcf2a0 100644--- a/litellm/llms/vertex_ai/batches/transformation.py+++ b/litellm/llms/vertex_ai/batches/transformation.py@@ -1,7 +1,9 @@from typing import Any, Dict, Optional+from urllib.parse import unquotefrom litellm._uuid import uuidfrom litellm.llms.vertex_ai.common_utils import (+ VertexAIError,_convert_vertex_datetime_to_openai_datetime,)from litellm.types.llms.openai import BatchJobStatus, CreateBatchRequest@@ -199,15 +201,39 @@ class VertexAIBatchTransformation:gcs_file_uri format: gs://litellm-testing-bucket/litellm-vertex-files/publishers/google/models/gemini-1.5-flash-001/e9412502-2c91-42a6-8e61-f5c294cc0fc8returns: "publishers/google/models/gemini-1.5-flash-001"++ Raises a 400 `VertexAIError` when the uri carries no parseable model path."""- from urllib.parse import unquote+ model = cls._parse_model_from_gcs_file(gcs_file_uri)+ if model is None:+ raise VertexAIError(+ status_code=400,+ message=(+ "Vertex AI batch creation requires the model to be part of `input_file_id`, but "+ f"'{gcs_file_uri}' contains no 'publishers/<publisher>/models/<model>' path segment. "+ "Either upload the input file through LiteLLM (POST /v1/files with "+ "custom_llm_provider=vertex_ai), which encodes the model into the returned file id, or "+ "pass a uri of the form "+ "gs://<bucket>/<prefix>/publishers/<publisher>/models/<model>/<file>"+ ),+ )+ return model- decoded_uri = unquote(gcs_file_uri)+ @classmethod+ def _parse_model_from_gcs_file(cls, gcs_file_uri: str) -> str | None:+ """+ Returns the `publishers/<publisher>/models/<model>` path from a gcs uri, or None if the uri+ does not contain one.+ """+ _, separator, model_path = unquote(gcs_file_uri).partition("publishers/")+ if not separator:+ return None- model_path = decoded_uri.split("publishers/")[1]parts = model_path.split("/")- model = f"publishers/{'/'.join(parts[:3])}"- return model+ if len(parts) < 3 or parts[1] != "models" or not parts[2]:+ return None++ return f"publishers/{'/'.join(parts[:3])}"@classmethoddef is_unmanaged_gcs_batch_input_file_id(cls, input_file_id: Optional[str]) -> bool:@@ -216,7 +242,11 @@ class VertexAIBatchTransformation:LiteLLM-managed unified file id) with a `publishers/` model path that`_get_model_from_gcs_file` can parse."""- return input_file_id is not None and input_file_id.startswith("gs://") and "publishers/" in input_file_id+ return (+ input_file_id is not None+ and input_file_id.startswith("gs://")+ and cls._parse_model_from_gcs_file(input_file_id) is not None+ )@classmethoddef get_bare_model_name_from_gcs_file(cls, gcs_file_uri: str) -> str:diff --git a/tests/test_litellm/llms/vertex_ai/batches/test_handler.py b/tests/test_litellm/llms/vertex_ai/batches/test_handler.pyindex cacea234777..b9fb5dfe3c5 100644--- a/tests/test_litellm/llms/vertex_ai/batches/test_handler.py+++ b/tests/test_litellm/llms/vertex_ai/batches/test_handler.py@@ -40,6 +40,7 @@ sys.path.insert(0, os.path.abspath("../../../../.."))from litellm.llms.vertex_ai.batches.handler import ( # noqa: E402VertexAIBatchPrediction,)+from litellm.llms.vertex_ai.common_utils import VertexAIError # noqa: E402from litellm.types.utils import LiteLLMBatch # noqa: E402HMOD = "litellm.llms.vertex_ai.batches.handler"@@ -184,7 +185,7 @@ def test_create_batch_sync_non_200_raises():client.post.return_value = _http_response(status_code=500)with patch(f"{HMOD}._get_httpx_client", return_value=client):- with pytest.raises(Exception, match="Error: 500"):+ with pytest.raises(VertexAIError, match="Error: 500") as exc_info:h.create_batch(_is_async=False,create_batch_data=CREATE_DATA,@@ -196,6 +197,32 @@ def test_create_batch_sync_non_200_raises():max_retries=None,)+ assert exc_info.value.status_code == 500+ assert "error text" in str(exc_info.value)+++def test_create_batch_input_file_id_without_model_raises_400_before_post():+ """A gs:// uri with no publishers/<publisher>/models/<model> path is a 400, not a bare 500."""+ h = _make_handler()+ client = MagicMock()++ with patch(f"{HMOD}._get_httpx_client", return_value=client):+ with pytest.raises(VertexAIError) as exc_info:+ h.create_batch(+ _is_async=False,+ create_batch_data={"input_file_id": "gs://bucket/batch-input.jsonl"},+ api_base=None,+ vertex_credentials=None,+ vertex_project=PROJECT,+ vertex_location=LOCATION,+ timeout=600.0,+ max_retries=None,+ )++ assert exc_info.value.status_code == 400+ assert "gs://bucket/batch-input.jsonl" in str(exc_info.value)+ client.post.assert_not_called()+def test_create_batch_async_non_200_raises():h = _make_handler()@@ -216,9 +243,12 @@ def test_create_batch_async_non_200_raises():timeout=600.0,max_retries=None,)- with pytest.raises(Exception, match="Error: 403"):+ with pytest.raises(VertexAIError, match="Error: 403") as exc_info:_run(coro)+ assert exc_info.value.status_code == 403+ assert "error text" in str(exc_info.value)+# =========================================================================== ## retrieve_batch@@ -292,7 +322,7 @@ def test_retrieve_batch_sync_non_200_raises():patch(f"{HMOD}._get_httpx_client", return_value=MagicMock()),patch(f"{HMOD}.safe_get", return_value=_http_response(status_code=404)),):- with pytest.raises(Exception, match="Error: 404"):+ with pytest.raises(VertexAIError, match="Error: 404"):h.retrieve_batch(_is_async=False,batch_id=BATCH_ID,@@ -438,7 +468,7 @@ def test_list_batches_sync_non_200_raises():client.get.return_value = _http_response(status_code=500)with patch(f"{HMOD}._get_httpx_client", return_value=client):- with pytest.raises(Exception, match="Error: 500"):+ with pytest.raises(VertexAIError, match="Error: 500"):h.list_batches(_is_async=False,after=None,@@ -530,7 +560,7 @@ def test_cancel_batch_sync_cancel_post_non_200_raises():client.post.return_value = _http_response(status_code=500)with patch(f"{HMOD}._get_httpx_client", return_value=client):- with pytest.raises(Exception, match="Error: 500"):+ with pytest.raises(VertexAIError, match="Error: 500"):h.cancel_batch(_is_async=False,batch_id=BATCH_ID,@@ -552,7 +582,7 @@ def test_cancel_batch_sync_retrieve_non_200_raises():client.get.return_value = _http_response(status_code=404)with patch(f"{HMOD}._get_httpx_client", return_value=client):- with pytest.raises(Exception, match="Error: 404"):+ with pytest.raises(VertexAIError, match="Error: 404"):h.cancel_batch(_is_async=False,batch_id=BATCH_ID,@@ -672,7 +702,7 @@ def test_async_retrieve_batch_non_200_raises():timeout=600.0,max_retries=None,)- with pytest.raises(Exception, match="Error: 500"):+ with pytest.raises(VertexAIError, match="Error: 500"):_run(coro)@@ -726,7 +756,7 @@ def test_async_list_batches_non_200_raises():timeout=600.0,max_retries=None,)- with pytest.raises(Exception, match="Error: 500"):+ with pytest.raises(VertexAIError, match="Error: 500"):_run(coro)@@ -779,7 +809,7 @@ def test_async_cancel_batch_httpstatuserror_and_retrieve_non_200():timeout=600.0,max_retries=None,)- with pytest.raises(Exception, match="Error: 500"):+ with pytest.raises(VertexAIError, match="Error: 500"):_run(coro)async_client_post500.get.assert_not_awaited()@@ -801,5 +831,5 @@ def test_async_cancel_batch_httpstatuserror_and_retrieve_non_200():timeout=600.0,max_retries=None,)- with pytest.raises(Exception, match="Error: 404"):+ with pytest.raises(VertexAIError, match="Error: 404"):_run(coro)diff --git a/tests/test_litellm/llms/vertex_ai/batches/test_transformation.py b/tests/test_litellm/llms/vertex_ai/batches/test_transformation.pyindex 1b37ade6b30..8352ec16389 100644--- a/tests/test_litellm/llms/vertex_ai/batches/test_transformation.py+++ b/tests/test_litellm/llms/vertex_ai/batches/test_transformation.py@@ -25,6 +25,7 @@ from litellm.llms.vertex_ai.batches.transformation import ( # noqa: E402VertexAIBatchTransformation,)from litellm.llms.vertex_ai.common_utils import ( # noqa: E402+ VertexAIError,_convert_vertex_datetime_to_openai_datetime,)from litellm.types.utils import LiteLLMBatch # noqa: E402@@ -69,6 +70,24 @@ def test_transform_openai_request_missing_input_file_id_raises():T.transform_openai_batch_request_to_vertex_ai_batch_request({})+ "input_file_id",+ [+ "gs://bucket/no-model-here.jsonl",+ "gs://bucket/publishers/google/gemini-1.5-flash-001/file-uuid",+ "gs://bucket/publishers/google/models",+ "gs://bucket/publishers/google/models//file-uuid",+ ],+)+def test_transform_openai_request_unparseable_model_raises_400(input_file_id: str):+ """An input_file_id with no parseable model path is a client error, not an IndexError -> 500."""+ with pytest.raises(VertexAIError) as exc_info:+ T.transform_openai_batch_request_to_vertex_ai_batch_request({"input_file_id": input_file_id})++ assert exc_info.value.status_code == 400+ assert input_file_id in str(exc_info.value)++# =========================================================================== ## transform_vertex_ai_batch_response_to_openai_batch_response# =========================================================================== #@@ -299,9 +318,29 @@ def test_get_model_from_gcs_file_url_encoded():assert T._get_model_from_gcs_file(encoded) == "publishers/google/models/gemini-1.5-flash-001"-def test_get_model_from_gcs_file_no_publishers_raises():- with pytest.raises(IndexError):+def test_get_model_from_gcs_file_no_publishers_raises_400():+ with pytest.raises(VertexAIError) as exc_info:T._get_model_from_gcs_file("gs://bucket/no-model-here.jsonl")+ assert exc_info.value.status_code == 400+++# =========================================================================== #+# is_unmanaged_gcs_batch_input_file_id+# =========================================================================== #+++ "input_file_id, expected",+ [+ (INPUT_FILE, True),+ (None, False),+ ("file-abc123", False),+ ("gs://bucket/no-model-here.jsonl", False),+ ("gs://bucket/publishers/google/gemini-1.5-flash-001/file-uuid", False),+ ],+)+def test_is_unmanaged_gcs_batch_input_file_id(input_file_id, expected):+ assert T.is_unmanaged_gcs_batch_input_file_id(input_file_id) is expected# =========================================================================== #