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(ocr): reject invalid req_format values as 400 on the SDK path
mateo-berri7ba78c9ea9dc
diff --git a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.pyindex 36963aee838..e7b94b3812b 100644--- a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py+++ b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py@@ -24,6 +24,7 @@ from litellm.constants import (AZURE_DOCUMENT_INTELLIGENCE_DEFAULT_DPI,AZURE_OPERATION_POLLING_TIMEOUT,)+from litellm.exceptions import UnsupportedParamsErrorfrom litellm.litellm_core_utils.url_utils import SSRFError, assert_same_origin, encode_url_path_segmentfrom litellm.llms.base_llm.ocr.transformation import (OCR_REQUEST_FORMAT_PARAM,@@ -133,12 +134,19 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig):**({"pages": normalized_pages} if normalized_pages else {}),**({"features": normalized_features} if normalized_features else {}),**(- {OCR_REQUEST_FORMAT_PARAM: parse_ocr_request_format(request_format)}+ {OCR_REQUEST_FORMAT_PARAM: self._parse_request_format(request_format, model)}if request_format is not Noneelse {}),}+ @staticmethod+ def _parse_request_format(request_format: object, model: str) -> OCRRequestFormat:+ try:+ return parse_ocr_request_format(request_format)+ except ValueError as e:+ raise UnsupportedParamsError(message=f"{e}", model=model, llm_provider="azure_ai") from e+@staticmethoddef _normalize_pages_param(pages: Any) -> str:"""diff --git a/litellm/ocr/main.py b/litellm/ocr/main.pyindex 3ff785c883c..b918f013700 100644--- a/litellm/ocr/main.py+++ b/litellm/ocr/main.py@@ -25,6 +25,7 @@ from litellm.llms.base_llm.ocr.transformation import (OCR_REQUEST_FORMAT_PARAM,BaseOCRConfig,OCRResponse,+ parse_ocr_request_format,)from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandlerfrom litellm.rust_bridge import ocr as rust_ocr_bridge@@ -128,11 +129,23 @@ def _prepare_ocr_request(litellm_params: Final = GenericLiteLLMParams.model_validate(kwargs)supported_params: Final = ocr_provider_config.get_supported_ocr_params(model=model)- if OCR_REQUEST_FORMAT_PARAM not in supported_params and kwargs.get(OCR_REQUEST_FORMAT_PARAM) == "native":- raise ValueError(- f"`{OCR_REQUEST_FORMAT_PARAM}='native'` is not supported for provider: {custom_llm_provider}, "- f"model: {model}"- )+ requested_format: Final = kwargs.get(OCR_REQUEST_FORMAT_PARAM)+ if requested_format is not None:+ try:+ parsed_format: Final = parse_ocr_request_format(requested_format)+ except ValueError as e:+ raise litellm.exceptions.UnsupportedParamsError(+ message=f"{e}", model=model, llm_provider=custom_llm_provider+ ) from e+ if OCR_REQUEST_FORMAT_PARAM not in supported_params and parsed_format == "native":+ raise litellm.exceptions.UnsupportedParamsError(+ message=(+ f"`{OCR_REQUEST_FORMAT_PARAM}='native'` is not supported for provider: {custom_llm_provider}, "+ f"model: {model}"+ ),+ model=model,+ llm_provider=custom_llm_provider,+ )non_default_params: Final = {}for param in supported_params:diff --git a/litellm/proxy/ocr_endpoints/endpoints.py b/litellm/proxy/ocr_endpoints/endpoints.pyindex 173fe6851a2..ebf4d988fdd 100644--- a/litellm/proxy/ocr_endpoints/endpoints.py+++ b/litellm/proxy/ocr_endpoints/endpoints.py@@ -154,9 +154,9 @@ async def _parse_multipart_form(request: Request) -> dict[str, Any]:return data-async def _parse_ocr_request(request: Request) -> dict[str, Any]:+async def _parse_ocr_request(request: Request) -> Mapping[str, Any]:"""Parse an OCR request and apply the `x-req-format` header, if any."""- return {**_with_request_format(await _parse_ocr_request_body(request), request)}+ return _with_request_format(await _parse_ocr_request_body(request), request)async def _parse_ocr_request_body(request: Request) -> dict[str, Any]:@@ -315,7 +315,7 @@ async def ocr(data: dict = {}try:# Parse request body (JSON or multipart form)- data = await _parse_ocr_request(request)+ data = dict(await _parse_ocr_request(request))# Process request using ProxyBaseLLMRequestProcessingprocessor = ProxyBaseLLMRequestProcessing(data=data)diff --git a/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py b/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.pyindex dfda159dda4..66f4f432eb8 100644--- a/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py+++ b/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py@@ -3,6 +3,8 @@ from unittest.mock import MagicMockimport httpximport pytest+from litellm.exceptions import UnsupportedParamsError+from litellm.llms.azure_ai.ocr.document_intelligence.transformation import (AzureDocumentIntelligenceOCRConfig,)@@ -249,12 +251,14 @@ def test_map_ocr_params_passes_through_req_format(req_format):assert config.map_ocr_params({"req_format": req_format}, {}, "prebuilt-layout") == {"req_format": req_format}-def test_map_ocr_params_rejects_unknown_req_format():+def test_map_ocr_params_rejects_unknown_req_format_as_bad_request():config = AzureDocumentIntelligenceOCRConfig()- with pytest.raises(ValueError, match="Invalid `req_format`"):+ with pytest.raises(UnsupportedParamsError, match="Invalid `req_format`") as exc_info:config.map_ocr_params({"req_format": "azure"}, {}, "prebuilt-layout")+ assert exc_info.value.status_code == 400+def test_get_complete_url_omits_req_format_query_param():config = AzureDocumentIntelligenceOCRConfig()diff --git a/tests/test_litellm/ocr/test_ocr_native_format.py b/tests/test_litellm/ocr/test_ocr_native_format.pyindex 2fec65d416a..463213a2071 100644--- a/tests/test_litellm/ocr/test_ocr_native_format.py+++ b/tests/test_litellm/ocr/test_ocr_native_format.py@@ -40,11 +40,26 @@ def test_rust_ocr_skipped_for_native_format():@pytest.mark.asyncio-async def test_native_format_rejected_for_provider_without_support():- with pytest.raises(Exception, match="not supported for provider"):+async def test_native_format_rejected_for_provider_without_support_as_bad_request():+ with pytest.raises(litellm.BadRequestError, match="not supported for provider") as exc_info:await litellm.aocr(model="mistral/mistral-ocr-latest",document=DOCUMENT,api_key="fake-key",req_format="native",)++ assert exc_info.value.status_code == 400+++async def test_unknown_format_rejected_for_provider_without_support_as_bad_request():+ with pytest.raises(litellm.BadRequestError, match="Invalid `req_format`") as exc_info:+ await litellm.aocr(+ model="mistral/mistral-ocr-latest",+ document=DOCUMENT,+ api_key="fake-key",+ req_format="raw",+ )++ assert exc_info.value.status_code == 400