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(proxy): return 400 naming the missing required param on POST /v1/batches
mateo-berrie4ce5269005e
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.pyindex 6952c0c6f89..623900322be 100644--- a/litellm/proxy/batches_endpoints/endpoints.py+++ b/litellm/proxy/batches_endpoints/endpoints.py@@ -40,6 +40,7 @@ from litellm.proxy.openai_files_endpoints.common_utils import (update_batch_in_database,validate_managed_id_requirement,)+from litellm.proxy.route_llm_request import raise_if_required_body_param_missingfrom litellm.proxy.utils import handle_exception_on_proxy, is_known_modelfrom litellm.repositories.table_repositories import ManagedFileRepositoryfrom litellm.types.llms.openai import LiteLLMBatchCreateRequest@@ -140,6 +141,8 @@ async def create_batch()data["metadata"] = sanitize_openai_provider_metadata(data.get("metadata"))+ raise_if_required_body_param_missing(route_type="acreate_batch", data=data)+## check if model is a loadbalanced modelrouter_model: str | None = Noneis_router_model = Falsediff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex b347360a939..c85325b6fa9 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -6,7 +6,7 @@ import httpxfrom fastapi import HTTPException, statusimport litellm-from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy._types import ProxyException, UserAPIKeyAuthfrom litellm.router_utils.common_utils import _is_proxy_admin_request# Client-supplied params that make the router or the call path fabricate a@@ -141,6 +141,7 @@ ROUTE_ENDPOINT_MAPPING: Final = {"aget_run": "/evals/{eval_id}/runs/{run_id}","acancel_run": "/evals/{eval_id}/runs/{run_id}/cancel","adelete_run": "/evals/{eval_id}/runs/{run_id}",+ "acreate_batch": "/batches",}@@ -152,27 +153,33 @@ class ProxyModelNotFoundError(HTTPException):super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)-REQUIRED_BODY_PARAM_BY_ROUTE: Final[Mapping[str, str]] = {- "acompletion": "messages",- "aembedding": "input",+REQUIRED_BODY_PARAMS_BY_ROUTE: Final[Mapping[str, tuple[str, ...]]] = {+ "acompletion": ("messages",),+ "aembedding": ("input",),+ "acreate_batch": ("input_file_id", "endpoint", "completion_window"),}-class ProxyMissingRequiredParamError(HTTPException):+class ProxyMissingRequiredParamError(ProxyException):def __init__(self, route: str, param: str):- detail: Final = {"error": f"{route}: Missing required parameter: '{param}'."}- super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)- self.type = "invalid_request_error"- self.param = param+ super().__init__(+ message=f"{route}: Missing required parameter: '{param}'.",+ type="invalid_request_error",+ param=param,+ code=status.HTTP_400_BAD_REQUEST,+ )def raise_if_required_body_param_missing(route_type: str, data: Mapping[str, object]) -> None:- required_param: Final = REQUIRED_BODY_PARAM_BY_ROUTE.get(route_type)- if required_param is None or data.get(required_param) is not None:+ missing_param: Final = next(+ (param for param in REQUIRED_BODY_PARAMS_BY_ROUTE.get(route_type, ()) if data.get(param) is None),+ None,+ )+ if missing_param is None:returnraise ProxyMissingRequiredParamError(route=ROUTE_ENDPOINT_MAPPING.get(route_type, route_type),- param=required_param,+ param=missing_param,)diff --git a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.pyindex 824654dcf66..bef111d62bc 100644--- a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py+++ b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py@@ -758,6 +758,36 @@ async def test_create__model_encoded_beats_loadbalancing(harness):harness.creds_resolver.assert_called_once_with(model_id="azure/gpt-4o")+# =========================================================================== #+# Missing required body params - 400 naming the field, never a 500 TypeError+# from acreate_batch() (https://github.com/BerriAI/litellm/issues/37146).+# =========================================================================== #+++ "body, missing_param",+ [+ ({"endpoint": "/v1/chat/completions", "completion_window": "24h"}, "input_file_id"),+ ({"input_file_id": "file-abc", "completion_window": "24h"}, "endpoint"),+ ({"input_file_id": "file-abc", "endpoint": "/v1/chat/completions"}, "completion_window"),+ ({}, "input_file_id"),+ ],+)+async def test_create__missing_required_param_is_400(harness, body, missing_param):+ set_body(harness, body)++ with pytest.raises(ProxyException) as exc_info:+ await call_create(harness)++ assert exc_info.value.code == "400"+ assert exc_info.value.type == "invalid_request_error"+ assert exc_info.value.param == missing_param+ assert exc_info.value.message == f"/batches: Missing required parameter: '{missing_param}'."+ harness.litellm_acreate.assert_not_called()+ harness.router_acreate.assert_not_called()++# =========================================================================== ## Team-level batch expiry enforcement (independent of routing).# =========================================================================== #diff --git a/tests/test_litellm/proxy/test_route_llm_request.py b/tests/test_litellm/proxy/test_route_llm_request.pyindex 08e26125bd3..fc3b14592cd 100644--- a/tests/test_litellm/proxy/test_route_llm_request.py+++ b/tests/test_litellm/proxy/test_route_llm_request.py@@ -1042,9 +1042,10 @@ async def test_route_request_override_enable_tag_filtering_beats_body_value():[("acompletion", "messages", "/chat/completions"),("aembedding", "input", "/embeddings"),+ ("acreate_batch", "input_file_id", "/batches"),],)[email protected]("data_extra", [{}, {"messages": None, "input": None}])[email protected]("data_extra", [{}, {"messages": None, "input": None, "input_file_id": None}])def test_raise_if_required_body_param_missing_rejects_missing_param(route_type, param, route, data_extra):from litellm.proxy.route_llm_request import (ProxyMissingRequiredParamError,@@ -1054,10 +1055,31 @@ def test_raise_if_required_body_param_missing_rejects_missing_param(route_type,with pytest.raises(ProxyMissingRequiredParamError) as exc_info:raise_if_required_body_param_missing(route_type=route_type, data={"model": "gpt-4o", **data_extra})- assert exc_info.value.status_code == 400+ assert exc_info.value.code == "400"assert exc_info.value.param == paramassert exc_info.value.type == "invalid_request_error"- assert exc_info.value.detail == {"error": f"{route}: Missing required parameter: '{param}'."}+ assert exc_info.value.message == f"{route}: Missing required parameter: '{param}'."+++ "data, param",+ [+ ({"endpoint": "/v1/chat/completions", "completion_window": "24h"}, "input_file_id"),+ ({"input_file_id": "file-abc", "completion_window": "24h"}, "endpoint"),+ ({"input_file_id": "file-abc", "endpoint": "/v1/chat/completions"}, "completion_window"),+ ({}, "input_file_id"),+ ],+)+def test_raise_if_required_body_param_missing_names_first_missing_batch_param(data, param):+ from litellm.proxy.route_llm_request import (+ ProxyMissingRequiredParamError,+ raise_if_required_body_param_missing,+ )++ with pytest.raises(ProxyMissingRequiredParamError) as exc_info:+ raise_if_required_body_param_missing(route_type="acreate_batch", data=data)++ assert exc_info.value.param == param@pytest.mark.parametrize(@@ -1069,6 +1091,10 @@ def test_raise_if_required_body_param_missing_rejects_missing_param(route_type,("aembedding", {"model": "text-embedding-3-small", "input": "hi"}),("arerank", {"model": "rerank-model"}),("aimage_generation", {"model": "dall-e-3"}),+ (+ "acreate_batch",+ {"input_file_id": "file-abc", "endpoint": "/v1/chat/completions", "completion_window": "24h"},+ ),],)def test_raise_if_required_body_param_missing_allows_valid_requests(route_type, data):@@ -1088,7 +1114,7 @@ async def test_route_request_rejects_chat_completion_without_messages():with pytest.raises(ProxyMissingRequiredParamError) as exc_info:await route_request({"model": "gpt-4o"}, llm_router, None, "acompletion")- assert exc_info.value.status_code == 400+ assert exc_info.value.code == "400"assert exc_info.value.param == "messages"llm_router.acompletion.assert_not_called()