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: port OCR request validation and upstream error mapping onto main's dispatch layout

Yujong Lee1f0c10147d18
diff --cc litellm/ocr/main.py
index c6371c0c33f,f0cf6cc82cc..06830ed4b53
--- a/litellm/ocr/main.py
+++ b/litellm/ocr/main.py
@@@ -3,81 -15,402 +15,409 @@@ from typing import Final, Protocol, cas
import httpx
- from litellm.llms.base_llm.ocr.transformation import OCRResponse
- from litellm.ocr import legacy
- from litellm.ocr.legacy import convert_file_document_to_url_document, get_mime_type
- from litellm.rust_bridge.bindings import native_exception_types
- from litellm.rust_bridge.configuration import rust_ocr_enabled
- from litellm.rust_bridge.ocr import LiteLLMOcrRequest
- from litellm.rust_bridge.ocr_lifecycle import select
+ import litellm
+ from litellm._logging import verbose_logger
+ from litellm.constants import request_timeout
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ 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 BaseLLMHTTPHandler
+ from litellm.types.router import GenericLiteLLMParams
+ from litellm.types.utils import CustomPricingLiteLLMParams
+ from litellm.utils import ProviderConfigManager, client
+
+ base_llm_http_handler: Final = BaseLLMHTTPHandler()
+
- __all__ = ("aocr", "convert_file_document_to_url_document", "get_mime_type", "ocr")
+ class FileReader(Protocol):
+ def read(self) -> bytes | str: ...
- def _bind_request(
+ @dataclass(frozen=True, slots=True)
+ class _PreparedOCRRequest:
+ model: str
+ document: Mapping[str, object]
+ api_key: str | None
+ api_base: str | None
+ custom_llm_provider: str
+ extra_headers: dict[str, object] | None
+ provider_config: BaseOCRConfig
+ optional_params: dict[str, object]
+ litellm_params: dict[str, object]
+ effective_timeout: float | httpx.Timeout
+ litellm_logging_obj: LiteLLMLoggingObj
+
+
+ def _prepare_ocr_request(
model: str,
document: Mapping[str, object],
- api_key: str | None = None,
- api_base: str | None = None,
- timeout: float | httpx.Timeout | None = None,
- custom_llm_provider: str | None = None,
- extra_headers: dict[str, object] | None = None,
- **kwargs: object, # kwargs-ok: public OCR accepts provider-specific options
- ) -> LiteLLMOcrRequest:
- return LiteLLMOcrRequest(
+ api_key: str | None,
+ api_base: str | None,
+ timeout: float | httpx.Timeout | None,
+ custom_llm_provider: str | None,
+ extra_headers: dict[str, object] | None,
+ kwargs: dict[str, object],
+ ) -> _PreparedOCRRequest:
+ litellm_logging_obj: Final = cast( # cast-ok: @client supplies the logging object; preserve legacy failure behavior
+ LiteLLMLoggingObj, kwargs.pop("litellm_logging_obj")
+ )
+ litellm_call_id: Final = cast( # cast-ok: @client supplies the call id without coercion
+ str | None, kwargs.get("litellm_call_id", None)
+ )
+
+ if not isinstance(document, dict):
- raise ValueError(f"document must be a dict with 'type' and URL/file field, got {type(document)}")
-
- doc_type = document.get("type")
++ raise litellm.BadRequestError(
++ message="document must be a dict with 'type' and URL/file field",
++ model=model,
++ llm_provider=_error_provider(model, custom_llm_provider) or "",
++ )
+
- if doc_type == "file":
- document = convert_file_document_to_url_document(document)
- doc_type = document.get("type")
++ normalized_document: Final = (
++ convert_file_document_to_url_document(document) if document.get("type") == "file" else document
++ )
++ doc_type: Final = normalized_document.get("type")
+
- if doc_type not in ["document_url", "image_url"]:
- raise ValueError(f"Invalid document type: {doc_type}. Must be 'document_url', 'image_url', or 'file'")
++ if doc_type not in ("document_url", "image_url"):
++ raise litellm.BadRequestError(
++ message=f"Invalid document type: {doc_type}. Must be 'document_url', 'image_url', or 'file'",
++ model=model,
++ llm_provider=_error_provider(model, custom_llm_provider) or "",
++ )
++ if not normalized_document.get(doc_type):
++ raise litellm.BadRequestError(
++ message="Document URL is required",
++ model=model,
++ llm_provider=_error_provider(model, custom_llm_provider) or "",
++ )
+
+ (
+ model,
+ custom_llm_provider,
+ dynamic_api_key,
+ dynamic_api_base,
+ ) = litellm.get_llm_provider(
model=model,
- document=document,
+ custom_llm_provider=custom_llm_provider,
+ api_base=api_base,
+ api_key=api_key,
+ )
+
+ ocr_provider_config: Final = ProviderConfigManager.get_provider_ocr_config(
+ model=model,
+ provider=litellm.LlmProviders(custom_llm_provider),
+ )
+
+ if ocr_provider_config is None:
+ raise ValueError(f"OCR is not supported for provider: {custom_llm_provider}")
+
+ resolved_api_key, resolved_api_base = ocr_provider_config.resolve_connection_params(
api_key=api_key,
api_base=api_base,
- timeout=timeout,
+ dynamic_api_key=dynamic_api_key,
+ dynamic_api_base=dynamic_api_base,
+ )
+
+ verbose_logger.debug("OCR call - model: %s, provider: %s", model, custom_llm_provider)
+
+ litellm_params: Final = GenericLiteLLMParams.model_validate(kwargs)
+
+ supported_params: Final = ocr_provider_config.get_supported_ocr_params(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)
++ 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:
- if param in kwargs:
- non_default_params[param] = kwargs.pop(param)
-
- optional_params: Final = ocr_provider_config.map_ocr_params(
- non_default_params=non_default_params,
- optional_params={},
- model=model,
++
++ non_default_params: Final = {param: kwargs.pop(param) for param in supported_params if param in kwargs}
++
++ try:
++ mapped_params: Final = ocr_provider_config.map_ocr_params(
++ non_default_params=non_default_params,
++ optional_params={},
++ model=model,
++ )
++ except ValueError as error:
++ raise litellm.BadRequestError(message=str(error), model=model, llm_provider=custom_llm_provider) from error
++ optional_params: Final = (
++ mapped_params if requested_format is None else {**mapped_params, OCR_REQUEST_FORMAT_PARAM: requested_format}
+ )
+
+ verbose_logger.debug("OCR optional_params after mapping: %s", optional_params)
+
+ effective_timeout: Final = timeout or request_timeout
+
+ litellm_logging_obj.update_from_kwargs(
+ kwargs=kwargs,
+ model=model,
+ optional_params=optional_params,
+ litellm_params={
+ "litellm_call_id": litellm_call_id,
+ "api_base": resolved_api_base,
+ **litellm_params.model_dump(include=frozenset(CustomPricingLiteLLMParams.model_fields), exclude_none=True),
+ },
+ custom_llm_provider=custom_llm_provider,
+ )
+
+ return _PreparedOCRRequest(
+ model=model,
- document=document,
++ document=normalized_document,
+ api_key=resolved_api_key,
+ api_base=resolved_api_base,
custom_llm_provider=custom_llm_provider,
extra_headers=extra_headers,
- kwargs=kwargs,
+ provider_config=ocr_provider_config,
+ optional_params=cast(
+ dict[str, object], optional_params
+ ), # cast-ok: provider configs return heterogeneous OCR options
+ litellm_params=dict(litellm_params),
+ effective_timeout=effective_timeout,
+ litellm_logging_obj=litellm_logging_obj,
)
- def _public_request(name: str, args: tuple[object, ...], kwargs: dict[str, object]) -> LiteLLMOcrRequest:
+ def _error_provider(model: str, custom_llm_provider: str | None) -> str | None:
+ if custom_llm_provider is not None:
+ return custom_llm_provider
+ prefix: Final = model.partition("/")[0]
- if prefix in {"mistral", "azure_ai", "vertex_ai"}:
++ if prefix in ("mistral", "azure_ai", "vertex_ai"):
+ return prefix
+ return "mistral" if model.startswith("mistral-ocr") else None
+
+
+ @client
+ async def aocr(
+ model: str,
+ document: Mapping[str, object],
+ api_key: str | None = None,
+ api_base: str | None = None,
+ timeout: float | httpx.Timeout | None = None,
+ custom_llm_provider: str | None = None,
+ extra_headers: dict[str, object] | None = None,
+ **kwargs: object, # kwargs-ok: public OCR accepts provider-specific options
+ ) -> OCRResponse:
+ completion_kwargs: Final[dict[str, object]] = {
+ "model": model,
+ "document": document,
+ "api_key": api_key,
+ "api_base": api_base,
+ "timeout": timeout,
+ "custom_llm_provider": custom_llm_provider,
+ "extra_headers": extra_headers,
+ "kwargs": kwargs,
+ }
try:
- return _bind_request(*args, **kwargs) # pyright: ignore[reportArgumentType] # Python binds the public arguments before native validation
- except TypeError as error:
- raise TypeError(str(error).replace("_bind_request()", f"{name}()")) from None
+ prepared: Final = _prepare_ocr_request(
+ model=model,
+ document=document,
+ api_key=api_key,
+ api_base=api_base,
+ timeout=timeout,
+ custom_llm_provider=custom_llm_provider,
+ extra_headers=extra_headers,
+ kwargs=kwargs,
+ )
+ model = prepared.model
+ custom_llm_provider = prepared.custom_llm_provider
- completion_kwargs.update({"model": model, "custom_llm_provider": custom_llm_provider})
++ completion_kwargs.update(model=model, custom_llm_provider=custom_llm_provider)
+ response = base_llm_http_handler.ocr(
+ model=prepared.model,
+ document=cast( # cast-ok: preserve legacy document fields for provider validation
+ dict[str, str], prepared.document
+ ),
+ optional_params=prepared.optional_params,
+ timeout=prepared.effective_timeout,
+ logging_obj=prepared.litellm_logging_obj,
+ api_key=prepared.api_key,
+ api_base=prepared.api_base,
+ custom_llm_provider=prepared.custom_llm_provider,
+ aocr=True,
+ headers=prepared.extra_headers,
+ provider_config=prepared.provider_config,
+ litellm_params=prepared.litellm_params,
+ )
- def ocr(
- *args: object,
- **kwargs: object, # kwargs-ok: preserve the public OCR call shape
- ) -> OCRResponse | Coroutine[object, object, OCRResponse]:
- request: Final = _public_request("ocr", args, kwargs)
- native: Final = select(request) if rust_ocr_enabled() else None
- if native is not None:
- try:
- return cast( # cast-ok: False selects the synchronous result
- OCRResponse, native(request, args, kwargs, False)
- )
- except _decline_types():
- pass
- fallback: Final = cast( # cast-ok: forward the original call shape through the legacy @client decorator
- Callable[..., OCRResponse | Coroutine[object, object, OCRResponse]], legacy.ocr
+ if asyncio.iscoroutine(response):
+ response = await response
+
+ if response is None:
+ raise ValueError(f"Got an unexpected None response from the OCR API: {response}")
+
+ return response
+ except Exception as e:
+ error_provider: Final = _error_provider(model, custom_llm_provider)
+ error_model: Final = model.removeprefix(f"{error_provider}/") if error_provider else model
+ raise litellm.exception_type(
+ model=error_model,
+ custom_llm_provider=error_provider,
+ original_exception=e,
+ completion_kwargs=completion_kwargs,
+ extra_kwargs=kwargs,
+ )
+
+
+ _MIME_PATTERN: Final = re.compile(r"^[\w.+-]+/[\w.+-]+$")
+
+ _MIME_TYPE_MAP: Final = MappingProxyType(
+ {
+ ".pdf": "application/pdf",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".tiff": "image/tiff",
+ ".tif": "image/tiff",
+ ".bmp": "image/bmp",
+ }
+ )
+
+
+ def get_mime_type(file_path: str) -> str:
+ ext: Final = os.path.splitext(file_path)[1].lower()
+ mime: Final = _MIME_TYPE_MAP.get(ext)
+ if mime:
+ return mime
+ guessed, _ = mimetypes.guess_type(file_path)
+ return guessed or "application/octet-stream"
+
+
+ def _read_file(file_input: object) -> tuple[bytes, str, str | None]:
+ if isinstance(file_input, str):
+ raise ValueError(
+ "OCR file input does not accept bare str values. Pass bytes, "
+ "a pathlib.Path, or a file-like object. To OCR a local file "
+ "from a path, call open(path, 'rb') yourself."
+ )
+ if isinstance(file_input, os.PathLike):
+ file_path: Final = str(cast(object, file_input)) # cast-ok: preserve staging's str(PathLike) conversion
+ if not os.path.isfile(file_path):
+ raise FileNotFoundError(f"File not found: {file_path}")
+ mime_type: Final = get_mime_type(file_path)
+ with open(file_path, "rb") as stream:
+ return stream.read(), mime_type, os.path.basename(file_path)
+ if isinstance(file_input, bytes):
+ return file_input, "application/octet-stream", None
+ if isinstance(file_input, IOBase) or hasattr(file_input, "read"):
+ file_name: Final = cast( # cast-ok: retain legacy validation and errors for file-like metadata
+ str | None, getattr(file_input, "name", None)
+ )
+ inferred_mime: Final = get_mime_type(file_name) if file_name else "application/octet-stream"
+ reader: Final = cast(FileReader, file_input) # cast-ok: legacy accepts duck-typed file readers
+ content: Final = reader.read()
+ return content.encode("utf-8") if isinstance(content, str) else content, inferred_mime, file_name
+ raise ValueError(
+ f"Unsupported file input type: {type(file_input)}. Expected pathlib.Path, bytes, or a file-like object."
)
- return fallback(*args, **kwargs)
- async def aocr(*args: object, **kwargs: object) -> OCRResponse: # kwargs-ok: preserve the public OCR call shape
- request: Final = _public_request("aocr", args, kwargs)
- native: Final = select(request) if rust_ocr_enabled() else None
- if native is not None:
- try:
- return await cast( # cast-ok: True selects the asynchronous result
- Awaitable[OCRResponse], native(request, args, kwargs, True)
- )
- except _decline_types():
- pass
- fallback: Final = cast( # cast-ok: forward the original call shape through the legacy @client decorator
- Callable[..., Awaitable[OCRResponse]], legacy.aocr
+ def convert_file_document_to_url_document(document: Mapping[str, object]) -> dict[str, str]:
+ file_input: Final = document.get("file")
+ if file_input is None:
+ raise ValueError(
+ "document with type='file' must include a 'file' field containing "
+ "a pathlib.Path, file-like object, or bytes"
+ )
+ file_bytes, inferred_mime, file_name = _read_file(file_input)
+ if not file_bytes:
+ raise ValueError("File is empty or could not be read")
+ mime_type: Final = cast( # cast-ok: keep staging's MIME validation errors
+ str, document.get("mime_type", inferred_mime)
)
- return await fallback(*args, **kwargs)
+ if not _MIME_PATTERN.match(mime_type):
+ raise ValueError(f"Invalid MIME type: {mime_type}")
+
+ base64_data: Final = base64.b64encode(file_bytes).decode("utf-8")
+ data_uri: Final = f"data:{mime_type};base64,{base64_data}"
+
+ if mime_type.startswith("image/"):
+ verbose_logger.debug(
+ "OCR file input: Converted file to image_url data URI (mime=%s, size=%s bytes, name=%s)",
+ mime_type,
+ len(file_bytes),
+ file_name,
+ )
+ return {"type": "image_url", "image_url": data_uri}
+
+ verbose_logger.debug(
+ "OCR file input: Converted file to document_url data URI (mime=%s, size=%s bytes, name=%s)",
+ mime_type,
+ len(file_bytes),
+ file_name,
+ )
+ return {"type": "document_url", "document_url": data_uri}
+
+
+ @client
+ def ocr(
+ model: str,
+ document: Mapping[str, object],
+ api_key: str | None = None,
+ api_base: str | None = None,
+ timeout: float | httpx.Timeout | None = None,
+ custom_llm_provider: str | None = None,
+ extra_headers: dict[str, object] | None = None,
+ **kwargs: object, # kwargs-ok: public OCR accepts provider-specific options
+ ) -> OCRResponse | Coroutine[object, object, OCRResponse]:
+ completion_kwargs: Final[dict[str, object]] = {
+ "model": model,
+ "document": document,
+ "api_key": api_key,
+ "api_base": api_base,
+ "timeout": timeout,
+ "custom_llm_provider": custom_llm_provider,
+ "extra_headers": extra_headers,
+ "kwargs": kwargs,
+ }
+ try:
+ _is_async: Final = kwargs.pop("aocr", False) is True
+ completion_kwargs["aocr"] = _is_async
+ prepared: Final = _prepare_ocr_request(
+ model=model,
+ document=document,
+ api_key=api_key,
+ api_base=api_base,
+ kwargs=kwargs,
+ custom_llm_provider=custom_llm_provider,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ )
+ model = prepared.model
+ custom_llm_provider = prepared.custom_llm_provider
- completion_kwargs.update({"model": model, "custom_llm_provider": custom_llm_provider})
++ completion_kwargs.update(model=model, custom_llm_provider=custom_llm_provider)
+ response: Final = base_llm_http_handler.ocr(
+ model=prepared.model,
+ document=cast( # cast-ok: preserve legacy document fields for provider validation
+ dict[str, str], prepared.document
+ ),
+ optional_params=prepared.optional_params,
+ timeout=prepared.effective_timeout,
+ logging_obj=prepared.litellm_logging_obj,
+ api_key=prepared.api_key,
+ api_base=prepared.api_base,
+ custom_llm_provider=prepared.custom_llm_provider,
+ aocr=_is_async,
+ headers=prepared.extra_headers,
+ provider_config=prepared.provider_config,
+ litellm_params=prepared.litellm_params,
+ )
- def _decline_types() -> tuple[type[BaseException], ...]:
- exception_types: Final = native_exception_types()
- return (exception_types[0],) if exception_types is not None else ()
+ return response
+ except Exception as e:
+ error_provider: Final = _error_provider(model, custom_llm_provider)
+ error_model: Final = model.removeprefix(f"{error_provider}/") if error_provider else model
+ raise litellm.exception_type(
+ model=error_model,
+ custom_llm_provider=error_provider,
+ original_exception=e,
+ completion_kwargs=completion_kwargs,
+ extra_kwargs=kwargs,
+ )
diff --cc litellm/rust_bridge/ocr/callbacks.py
index 00000000000,c30943e6fd7..4e6a2d054af
mode 000000,100644..100644
--- a/litellm/rust_bridge/ocr/callbacks.py
+++ b/litellm/rust_bridge/ocr/callbacks.py
@@@ -1,0 -1,31 +1,65 @@@
+ from __future__ import annotations
+
+ from collections.abc import Mapping
+ from types import MappingProxyType
+ from typing import Final
+
-from pydantic import TypeAdapter
++import httpx
++from pydantic import TypeAdapter, ValidationError
+
++import litellm
+ from litellm.llms.base_llm.ocr.transformation import PROVIDER_NATIVE_RESPONSE_KEY, OCRResponse
+ from litellm.rust_bridge import failures
+ from litellm.rust_bridge.ocr.entrypoints import LiteLLMOcrRequest
+
+ _RESPONSE_ADAPTER: Final = TypeAdapter(dict[str, object])
++_UPSTREAM_ARGS: Final = TypeAdapter(tuple[int, str])
++_UPSTREAM_HEADERS: Final = TypeAdapter(list[tuple[str, str]])
++
++
++class UpstreamFailure(Exception):
++ def __init__(self, response: httpx.Response, cause: Exception) -> None:
++ super().__init__(str(cause))
++ self.message: Final = str(cause)
++ self.response: Final = response
++ self.status_code: Final = response.status_code
++ self.__cause__ = cause
++
++
++def _upstream_failure(error: Exception) -> Exception:
++ try:
++ status, body = _UPSTREAM_ARGS.validate_python(error.args)
++ headers: Final = _UPSTREAM_HEADERS.validate_python(getattr(error, "headers", None))
++ except ValidationError:
++ return error
++ return UpstreamFailure(httpx.Response(status, content=body.encode(), headers=headers), error)
+
+
+ def response(value: Mapping[str, object]) -> OCRResponse:
+ provider_native_response: Final = value.get(PROVIDER_NATIVE_RESPONSE_KEY)
+ normalized: Final = OCRResponse.model_validate(
+ MappingProxyType({key: item for key, item in value.items() if key != PROVIDER_NATIVE_RESPONSE_KEY})
+ )
+ if isinstance(provider_native_response, Mapping):
+ normalized.set_provider_native_response(_RESPONSE_ADAPTER.validate_python(provider_native_response))
+ return normalized
+
+
+ def arguments(request: LiteLLMOcrRequest) -> Mapping[str, object]:
+ return request.kwargs
+
+
+ def map_failure(error: Exception, request: LiteLLMOcrRequest, request_provider: str) -> Exception:
- return failures.map_failure(error, request.model, request_provider, arguments(request))
++ if getattr(error, "ocr_request_format_error", False):
++ return litellm.UnsupportedParamsError(
++ message=f"Invalid `req_format`: {request.kwargs.get('req_format')!r}. Expected 'native' or 'litellm'.",
++ model=request.model.removeprefix(f"{request_provider}/"),
++ llm_provider=request_provider,
++ )
++ original: Final = _upstream_failure(error)
++ public_error: Final = failures.map_failure(original, request.model, request_provider, arguments(request))
++ if isinstance(original, UpstreamFailure) and public_error.__context__ is original:
++ public_error.response = original.response
++ public_error.status_code = original.status_code
++ public_error.__context__ = error
++ return public_error
diff --cc tests/test_litellm/ocr/test_main.py
index 4b0b78f5a0f,3fd0d05be4d..712a3438ddd
--- a/tests/test_litellm/ocr/test_main.py
+++ b/tests/test_litellm/ocr/test_main.py
@@@ -257,3 -257,70 +257,66 @@@ def test_direct_ocr_call_bills_request_
)
assert logging_obj._response_cost_calculator(result=response) == pytest.approx(0.05 * 3)
+
+
+ def _prepare(model: str, document: object, **kwargs: object) -> object:
+ return _prepare_ocr_request(
+ model=model,
+ document=document, # pyright: ignore[reportArgumentType] # exercises the runtime guard for untyped callers
+ api_key="test-key",
+ api_base=None,
+ timeout=None,
+ custom_llm_provider=None,
+ extra_headers=None,
+ kwargs={"litellm_logging_obj": Mock(), **kwargs},
+ )
+
+
+ @pytest.mark.parametrize(
+ ("document", "match"),
+ (
+ ("https://example.com/file.pdf", "document must be a dict"),
+ ({"type": "video_url", "video_url": "https://example.com/clip.mp4"}, "Invalid document type: video_url"),
+ ),
+ )
+ def test_prepare_ocr_request_rejects_malformed_documents(document: object, match: str) -> None:
- with pytest.raises(ValueError, match=match):
++ with pytest.raises(litellm.BadRequestError, match=match):
+ _prepare("mistral/mistral-ocr-latest", document)
+
+
+ def test_prepare_ocr_request_rejects_provider_without_ocr_support() -> None:
+ with pytest.raises(ValueError, match="OCR is not supported for provider: openai"):
+ _prepare("openai/gpt-4o", dict(PRICING_DOCUMENT))
+
+
- ("request_format", "match"),
- (("markdown", "Invalid `req_format`"), ("native", "`req_format='native'` is not supported")),
-)
-def test_prepare_ocr_request_rejects_unsupported_request_format(request_format: str, match: str) -> None:
- with pytest.raises(litellm.UnsupportedParamsError, match=match):
- _prepare("mistral/mistral-ocr-latest", dict(PRICING_DOCUMENT), req_format=request_format)
++def test_prepare_ocr_request_rejects_invalid_request_format() -> None:
++ with pytest.raises(litellm.UnsupportedParamsError, match="Invalid `req_format`"):
++ _prepare("mistral/mistral-ocr-latest", dict(PRICING_DOCUMENT), req_format="markdown")
+
+
+ @pytest.mark.asyncio
+ async def test_python_none_provider_response_raises_public_error(
+ provider: Mock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from litellm.ocr import main
+
+ monkeypatch.setattr(main.base_llm_http_handler, "ocr", Mock(return_value=None))
+
+ with pytest.raises(litellm.APIConnectionError, match="unexpected None response") as error:
+ await litellm.aocr(model="mistral/mistral-ocr-latest", document=dict(PRICING_DOCUMENT), api_key="test-key")
+ assert error.value.llm_provider == "mistral"
+ assert provider.call_count == 0
+
+
+ @pytest.mark.parametrize(
+ ("model", "expected_provider"),
+ (("mistral-ocr-latest", "mistral"), ("azure_ai/doc-intelligence/prebuilt-layout", "azure_ai")),
+ )
+ def test_preparation_errors_map_to_public_exception_for_inferred_provider(
+ provider: Mock, model: str, expected_provider: str
+ ) -> None:
- with pytest.raises(litellm.APIConnectionError) as error:
++ with pytest.raises(litellm.BadRequestError) as error:
+ litellm.ocr(model=model, document="not-a-document") # pyright: ignore[reportArgumentType] # exercises the runtime guard
+ assert error.value.llm_provider == expected_provider
+ assert "document must be a dict" in str(error.value)
+ assert provider.call_count == 0