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
merge: origin/main into litellm_rust_bridge_declarative_route_catalog
Yujong Leec635399f6e3e
diff --cc litellm-rust/crates/python-bridge/src/routes/ocr/mod.rsindex f3683501a62,5eae8ccf33f..b7f9613a5a0--- a/litellm-rust/crates/python-bridge/src/routes/ocr/mod.rs+++ b/litellm-rust/crates/python-bridge/src/routes/ocr/mod.rs@@@ -7,6 -8,6 +7,5 @@@ mod projectuse pyo3::prelude::*;pub(super) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {- document::register(module)?;- value::register(module)?;lifecycle::register(module)}diff --cc litellm/ocr/dispatch.pyindex 9a492fd4458,00000000000..41ea9ee074bmode 100644,000000..100644--- a/litellm/ocr/dispatch.py+++ b/litellm/ocr/dispatch.py@@@ -1,89 -1,0 +1,89 @@@+from collections.abc import Awaitable, Callable, Coroutine, Mapping+from typing import Final, cast # noqa: TID251 # native binding selects a sync result or an async awaitable++import httpx++from litellm.llms.base_llm.ocr.transformation import OCRResponse+from litellm.ocr import main- from litellm.ocr.input import convert_file_document_to_url_document, get_mime_type++from litellm.ocr.main import convert_file_document_to_url_document, get_mime_type+from litellm.rust_bridge.catalog import Context, Route+from litellm.rust_bridge.dispatch import PublicDispatch+from litellm.rust_bridge.ocr.entrypoints import NATIVE_AOCR, NATIVE_OCR, LiteLLMOcrRequest++__all__ = ("aocr", "convert_file_document_to_url_document", "get_mime_type", "ocr")+++def _bind_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(+ 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,+ )+++def _public_request(name: str, args: tuple[object, ...], kwargs: Mapping[str, object]) -> LiteLLMOcrRequest:+ 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+++_DISPATCH: Final = PublicDispatch(+ route=Route.OCR,+ request=lambda args, kwargs: _public_request("ocr", args, kwargs),+ context=lambda request: _context(request),+ bypass=lambda request: request.kwargs.get("aocr") is True,+)++_ADISPATCH: Final = PublicDispatch(+ route=Route.OCR,+ request=lambda args, kwargs: _public_request("aocr", args, kwargs),+ context=lambda request: _context(request),+)+++def ocr(+ *args: object,+ **kwargs: object, # kwargs-ok: preserve the public OCR call shape+) -> OCRResponse | Coroutine[object, object, OCRResponse]:+ python_ocr: Final = cast( # cast-ok: forward the original call shape through the Python @client decorator+ Callable[..., OCRResponse | Coroutine[object, object, OCRResponse]], main.ocr+ )+ return _DISPATCH.run(+ args,+ kwargs,+ python=python_ocr,+ binding=NATIVE_OCR,+ native=lambda hook, request, call_args, call_kwargs: hook(request, call_args, call_kwargs),+ )+++async def aocr(*args: object, **kwargs: object) -> OCRResponse: # kwargs-ok: preserve the public OCR call shape+ fallback: Final = cast( # cast-ok: forward the original call shape through the Python @client decorator+ Callable[..., Awaitable[OCRResponse]], main.aocr+ )+ return await _ADISPATCH.arun(+ args,+ kwargs,+ python=fallback,+ binding=NATIVE_AOCR,+ native=lambda hook, request, call_args, call_kwargs: hook(request, call_args, call_kwargs),+ )+++def _context(request: LiteLLMOcrRequest) -> Context:+ return Context(Route.OCR, provider=request.custom_llm_provider, model=request.model)diff --cc litellm/ocr/main.pyindex a742be274b3,c6371c0c33f..f0cf6cc82cc--- a/litellm/ocr/main.py+++ b/litellm/ocr/main.py@@@ -1,174 -1,38 +1,177 @@@-from collections.abc import Awaitable, Callable, Coroutine, Mapping-from typing import Final, cast # noqa: TID251 # native binding selects a sync result or an async awaitable+"""+Main OCR function for LiteLLM.+"""++import asyncio+import base64+import mimetypes+import os+import re+from collections.abc import Coroutine, Mapping+from dataclasses import dataclass+from io import IOBase+from types import MappingProxyType- from typing import Final, cast # noqa: TID251 # adapters preserve the legacy untyped contracts++from typing import Final, Protocol, cast # noqa: TID251 # adapters preserve the legacy untyped contractsimport 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.ocr.input import FileReader+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")++ if doc_type == "file":+ document = convert_file_document_to_url_document(document)+ doc_type = 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'")++ (+ 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)+ 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,+ )++ 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,+ 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,)diff --cc litellm/proxy/ocr_endpoints/endpoints.pyindex 53ebbe91b54,dde3d5ceb50..981581919e4--- a/litellm/proxy/ocr_endpoints/endpoints.py+++ b/litellm/proxy/ocr_endpoints/endpoints.py@@@ -15,7 -15,7 +15,7 @@@ from litellm.llms.base_llm.ocr.transforOCRResponse,parse_ocr_request_format,)- from litellm.ocr.input import convert_upload_to_url_document, get_max_file_bytes-from litellm.ocr.legacy import convert_file_document_to_url_document, get_mime_type++from litellm.ocr.main import convert_file_document_to_url_document, get_mime_typefrom litellm.proxy._types import *from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_authfrom litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessingdiff --cc litellm/rust_bridge/_native.pyiindex 05bb417f079,32b20bb7931..488e278cca7--- a/litellm/rust_bridge/_native.pyi+++ b/litellm/rust_bridge/_native.pyi@@@ -17,17 -25,20 +17,7 @@@ def aocrrequest: LiteLLMOcrRequest,args: tuple[object, ...],kwargs: dict[str, object],- asynchronous: bool,-) -> OCRResponse | Coroutine[object, object, OCRResponse]: ...+) -> Coroutine[object, object, OCRResponse]: ...-- _OCR_MAX_FILE_BYTES: int-- def _ocr_upload_document(- file_content: bytes,- file_name: str | None = None,- content_type: str | None = None,- ) -> dict[str, str]: ...- def _ocr_file_document(document: Mapping[str, object]) -> dict[str, str]: ...- def _ocr_mime_type(file_name: str) -> str: ...def transcription(model: str,audio: object,@@@ -124,9 -134,7 +113,6 @@@ __all__ ="RustBridgeDeclined","RustUpstreamError","TokenCounter",- "_ocr_file_document",- "_ocr_mime_type",- "_ocr_upload_document",- "_ocr_lifecycle","achat_completions","amessages","aocr",diff --cc tests/test_litellm/ocr/test_ocr_file_input.pyindex 3526d8c00d6,8f82a64bd85..4ac27d286e1--- a/tests/test_litellm/ocr/test_ocr_file_input.py+++ b/tests/test_litellm/ocr/test_ocr_file_input.py@@@ -22,22 -21,7 +21,7 @@@ import orjsoimport pytestfrom starlette.datastructures import FormData- from litellm.ocr.input import convert_file_document_to_url_document, get_mime_type--- @pytest.fixture(autouse=True, params=["native", "disabled", "unavailable"])- def document_runtime(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> Generator[None]:- from litellm.rust_bridge import bindings, configuration-- configuration.reset_rust_configuration()- monkeypatch.delenv("LITELLM_RUST", raising=False)- if request.param == "disabled":- monkeypatch.setenv("LITELLM_RUST", "0")- monkeypatch.setattr(bindings, "get_native_bridge", Mock(side_effect=AssertionError("Rust is disabled")))- elif request.param == "unavailable":- monkeypatch.setattr(bindings, "get_native_bridge", lambda: None)- yield- configuration.reset_rust_configuration()-from litellm.ocr.legacy import convert_file_document_to_url_document, get_mime_type++from litellm.ocr.main import convert_file_document_to_url_document, get_mime_typeclass TestGetMimeType: