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
[Feat] /ocr - Add VertexAI OCR provider support + cost tracking (#16216)
Ishaan Jaff71c61c274f47
diff --git a/docs/my-website/docs/ocr.md b/docs/my-website/docs/ocr.mdindex 2cb87edc461..93cb74ee69f 100644--- a/docs/my-website/docs/ocr.md+++ b/docs/my-website/docs/ocr.md@@ -5,7 +5,7 @@| Cost Tracking | ✅ || Logging | ✅ (Basic Logging not supported) || Load Balancing | ✅ |-| Supported Providers | `mistral`, `azure_ai` |+| Supported Providers | `mistral`, `azure_ai`, `vertex_ai` |:::tip@@ -262,4 +262,5 @@ The response follows Mistral's OCR format with the following structure:|-------------|--------------------|| Mistral AI | [Usage](#quick-start) || Azure AI | [Usage](../docs/providers/azure_ocr) |+| Vertex AI | [Usage](../docs/providers/vertex_ocr) |diff --git a/docs/my-website/docs/providers/vertex_ocr.md b/docs/my-website/docs/providers/vertex_ocr.mdnew file mode 100644index 00000000000..4e3d4b0a063--- /dev/null+++ b/docs/my-website/docs/providers/vertex_ocr.md@@ -0,0 +1,237 @@+# Vertex AI OCR++## Overview++| Property | Details |+|-------|-------|+| Description | Vertex AI OCR provides document intelligence capabilities powered by Mistral, enabling text extraction from PDFs and images |+| Provider Route on LiteLLM | `vertex_ai/` |+| Supported Operations | `/ocr` |+| Link to Provider Doc | [Vertex AI ↗](https://cloud.google.com/vertex-ai)++Extract text from documents and images using Vertex AI's OCR models, powered by Mistral.++## Quick Start++### **LiteLLM SDK**++```python showLineNumbers title="SDK Usage"+import litellm+import os++# Set environment variables+os.environ["VERTEXAI_PROJECT"] = "your-project-id"+os.environ["VERTEXAI_LOCATION"] = "us-central1"++# OCR with PDF URL+response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={+ "type": "document_url",+ "document_url": "https://example.com/document.pdf"+ }+)++# Access extracted text+for page in response.pages:+ print(page.text)+```++### **LiteLLM PROXY**++```yaml showLineNumbers title="proxy_config.yaml"+model_list:+ - model_name: vertex-ocr+ litellm_params:+ model: vertex_ai/mistral-ocr-2505+ vertex_project: os.environ/VERTEXAI_PROJECT+ vertex_location: os.environ/VERTEXAI_LOCATION+ vertex_credentials: path/to/service-account.json # Optional+ model_info:+ mode: ocr+```++**Start Proxy**+```bash+litellm --config proxy_config.yaml+```++**Call OCR via Proxy**+```bash showLineNumbers title="cURL Request"+curl -X POST http://localhost:4000/ocr \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer your-api-key" \+ -d '{+ "model": "vertex-ocr",+ "document": {+ "type": "document_url",+ "document_url": "https://arxiv.org/pdf/2201.04234"+ }+ }'+```++## Authentication++Vertex AI OCR supports multiple authentication methods:++### Service Account JSON++```python showLineNumbers title="Service Account Auth"+response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={"type": "document_url", "document_url": "https://..."},+ vertex_project="your-project-id",+ vertex_location="us-central1",+ vertex_credentials="path/to/service-account.json"+)+```++### Application Default Credentials++```python showLineNumbers title="Default Credentials"+# Relies on GOOGLE_APPLICATION_CREDENTIALS environment variable+response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={"type": "document_url", "document_url": "https://..."},+ vertex_project="your-project-id",+ vertex_location="us-central1"+)+```++## Document Types++Vertex AI OCR supports both PDFs and images.++### PDF Documents++```python showLineNumbers title="PDF OCR"+response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={+ "type": "document_url",+ "document_url": "https://example.com/document.pdf"+ },+ vertex_project="your-project-id",+ vertex_location="us-central1"+)+```++### Image Documents++```python showLineNumbers title="Image OCR"+response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={+ "type": "image_url",+ "image_url": "https://example.com/image.png"+ },+ vertex_project="your-project-id",+ vertex_location="us-central1"+)+```++### Base64 Encoded Documents++```python showLineNumbers title="Base64 PDF"+import base64++# Read and encode PDF+with open("document.pdf", "rb") as f:+ pdf_base64 = base64.b64encode(f.read()).decode()++response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={+ "type": "document_url",+ "document_url": f"data:application/pdf;base64,{pdf_base64}"+ },+ vertex_project="your-project-id",+ vertex_location="us-central1"+)+```++## Supported Parameters++```python showLineNumbers title="All Parameters"+response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={ # Required: Document to process+ "type": "document_url",+ "document_url": "https://..."+ },+ vertex_project="your-project-id", # Required: GCP project ID+ vertex_location="us-central1", # Optional: Defaults to us-central1+ vertex_credentials="path/to/key.json", # Optional: Service account key+ include_image_base64=True, # Optional: Include base64 images+ pages=[0, 1, 2], # Optional: Specific pages to process+ image_limit=10 # Optional: Limit number of images+)+```++## Response Format++```python showLineNumbers title="Response Structure"+# Response has the following structure+response.pages # List of pages with extracted text+response.model # Model used+response.object # "ocr"+response.usage_info # Token usage information++# Access page content+for page in response.pages:+ print(f"Page {page.page_number}:")+ print(page.text)+```++## Async Support++```python showLineNumbers title="Async Usage"+import litellm++response = await litellm.aocr(+ model="vertex_ai/mistral-ocr-2505",+ document={+ "type": "document_url",+ "document_url": "https://example.com/document.pdf"+ },+ vertex_project="your-project-id",+ vertex_location="us-central1"+)+```++## Cost Tracking++LiteLLM automatically tracks costs for Vertex AI OCR:++- **Cost per page**: $0.0005 (based on $1.50 per 1,000 pages)++```python showLineNumbers title="View Cost"+response = litellm.ocr(+ model="vertex_ai/mistral-ocr-2505",+ document={"type": "document_url", "document_url": "https://..."},+ vertex_project="your-project-id"+)++# Access cost information+print(f"Cost: ${response._hidden_params.get('response_cost', 0)}")+```++## Important Notes++:::info URL Conversion+Vertex AI OCR endpoints don't have internet access. LiteLLM automatically converts public URLs to base64 data URIs before sending requests to Vertex AI.+:::++:::tip Regional Availability+Mistral OCR is available in multiple regions. Specify `vertex_location` to use a region closer to your data:+- `us-central1` (default)+- `europe-west1`+- `asia-southeast1`+:::++## Supported Models++- `mistral-ocr-2505` - Latest Mistral OCR model on Vertex AI++Use the Vertex AI provider prefix: `vertex_ai/<model-name>`+diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex 000751badff..84c10678242 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -470,6 +470,7 @@ const sidebars = {"providers/vertex_self_deployed","providers/vertex_image","providers/vertex_batch",+ "providers/vertex_ocr",]},{diff --git a/litellm/llms/base_llm/ocr/transformation.py b/litellm/llms/base_llm/ocr/transformation.pyindex 2fe8f3def75..c88783f97f5 100644--- a/litellm/llms/base_llm/ocr/transformation.py+++ b/litellm/llms/base_llm/ocr/transformation.py@@ -106,6 +106,7 @@ class BaseOCRConfig:model: str,api_key: Optional[str] = None,api_base: Optional[str] = None,+ litellm_params: Optional[dict] = None,**kwargs,) -> Dict:"""@@ -119,6 +120,7 @@ class BaseOCRConfig:api_base: Optional[str],model: str,optional_params: dict,+ litellm_params: Optional[dict] = None,**kwargs,) -> str:"""diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex dbcb81107d6..47715f7bc5b 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -1286,18 +1286,19 @@ class BaseLLMHTTPHandler:Returns: (headers, complete_url, data, files)"""from litellm.llms.base_llm.ocr.transformation import OCRRequestData-headers = provider_config.validate_environment(api_key=api_key,api_base=api_base,headers=headers or {},model=model,+ litellm_params=litellm_params,)complete_url = provider_config.get_complete_url(api_base=api_base,model=model,optional_params=optional_params,+ litellm_params=litellm_params,)# Transform the request to get data and files@@ -1358,12 +1359,14 @@ class BaseLLMHTTPHandler:api_base=api_base,headers=headers or {},model=model,+ litellm_params=litellm_params,)complete_url = provider_config.get_complete_url(api_base=api_base,model=model,optional_params=optional_params,+ litellm_params=litellm_params,)# Use async transform (providers can override this method if they need async operations)diff --git a/litellm/llms/mistral/ocr/transformation.py b/litellm/llms/mistral/ocr/transformation.pyindex f17c872f536..ed5e2359395 100644--- a/litellm/llms/mistral/ocr/transformation.py+++ b/litellm/llms/mistral/ocr/transformation.py@@ -74,6 +74,7 @@ class MistralOCRConfig(BaseOCRConfig):model: str,api_key: Optional[str] = None,api_base: Optional[str] = None,+ litellm_params: Optional[dict] = None,**kwargs,) -> Dict:"""@@ -104,6 +105,7 @@ class MistralOCRConfig(BaseOCRConfig):api_base: Optional[str],model: str,optional_params: dict,+ litellm_params: Optional[dict] = None,**kwargs,) -> str:"""diff --git a/litellm/llms/vertex_ai/ocr/__init__.py b/litellm/llms/vertex_ai/ocr/__init__.pynew file mode 100644index 00000000000..fa8c85da9c5--- /dev/null+++ b/litellm/llms/vertex_ai/ocr/__init__.py@@ -0,0 +1,5 @@+"""Vertex AI OCR module."""+from .transformation import VertexAIOCRConfig++__all__ = ["VertexAIOCRConfig"]+diff --git a/litellm/llms/vertex_ai/ocr/transformation.py b/litellm/llms/vertex_ai/ocr/transformation.pynew file mode 100644index 00000000000..520b9a09393--- /dev/null+++ b/litellm/llms/vertex_ai/ocr/transformation.py@@ -0,0 +1,284 @@+"""+Vertex AI Mistral OCR transformation implementation.+"""+from typing import Dict, Optional++from litellm._logging import verbose_logger+from litellm.litellm_core_utils.prompt_templates.image_handling import (+ async_convert_url_to_base64,+ convert_url_to_base64,+)+from litellm.llms.base_llm.ocr.transformation import DocumentType, OCRRequestData+from litellm.llms.mistral.ocr.transformation import MistralOCRConfig+from litellm.llms.vertex_ai.vertex_llm_base import VertexBase+from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES+++class VertexAIOCRConfig(MistralOCRConfig):+ """+ Vertex AI Mistral OCR transformation configuration.++ Vertex AI uses Mistral's OCR API format through the Mistral publisher endpoint.+ Inherits transformation logic from MistralOCRConfig since they use the same format.++ Reference: Vertex AI Mistral OCR documentation++ Important: Vertex AI OCR only supports base64 data URIs (data:image/..., data:application/pdf;base64,...).+ Regular URLs are not supported.+ """++ def __init__(self) -> None:+ super().__init__()+ self.vertex_base = VertexBase()++ def validate_environment(+ self,+ headers: Dict,+ model: str,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ litellm_params: Optional[dict] = None,+ **kwargs,+ ) -> Dict:+ """+ Validate environment and return headers for Vertex AI OCR.++ Vertex AI uses Bearer token authentication with access token from credentials.+ """+ # Extract Vertex AI parameters using safe helpers from VertexBase+ # Use safe_get_* methods that don't mutate litellm_params dict+ litellm_params = litellm_params or {}++ vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params)+ vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params=litellm_params)++ # Get access token from Vertex credentials+ access_token, project_id = self.vertex_base.get_access_token(+ credentials=vertex_credentials,+ project_id=vertex_project,+ )++ headers = {+ "Authorization": f"Bearer {access_token}",+ "Content-Type": "application/json",+ **headers,+ }++ return headers++ def get_complete_url(+ self,+ api_base: Optional[str],+ model: str,+ optional_params: dict,+ litellm_params: Optional[dict] = None,+ **kwargs,+ ) -> str:+ """+ Get complete URL for Vertex AI OCR endpoint.++ Vertex AI endpoint format:+ https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/mistralai/ocr++ Args:+ api_base: Vertex AI API base URL (optional)+ model: Model name (not used in URL construction)+ optional_params: Optional parameters+ litellm_params: LiteLLM parameters containing vertex_project, vertex_location++ Returns: Complete URL for Vertex AI OCR endpoint+ """+ # Extract Vertex AI parameters using safe helpers from VertexBase+ # Use safe_get_* methods that don't mutate litellm_params dict+ litellm_params = litellm_params or {}++ vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params)+ vertex_location = VertexBase.safe_get_vertex_ai_location(litellm_params=litellm_params)++ if vertex_project is None:+ raise ValueError(+ "Missing vertex_project - Set VERTEXAI_PROJECT environment variable or pass vertex_project parameter"+ )++ if vertex_location is None:+ vertex_location = "us-central1"++ # Get API base URL+ if api_base is None:+ api_base = f"https://{vertex_location}-aiplatform.googleapis.com"++ # Ensure no trailing slash+ api_base = api_base.rstrip("/")++ # Vertex AI OCR endpoint format for Mistral publisher+ # Format: https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/{region}/publishers/mistralai/models/{model}:rawPredict+ return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/mistralai/models/{model}:rawPredict"++ def _convert_url_to_data_uri_sync(self, url: str) -> str:+ """+ Synchronously convert a URL to a base64 data URI.++ Vertex AI OCR doesn't have internet access, so we need to fetch URLs+ and convert them to base64 data URIs.++ Args:+ url: The URL to convert++ Returns:+ Base64 data URI string+ """+ verbose_logger.debug(f"Vertex AI OCR: Converting URL to base64 data URI (sync): {url}")++ # Fetch and convert to base64 data URI+ # convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..."+ data_uri = convert_url_to_base64(url=url)++ verbose_logger.debug(f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})")++ return data_uri++ async def _convert_url_to_data_uri_async(self, url: str) -> str:+ """+ Asynchronously convert a URL to a base64 data URI.++ Vertex AI OCR doesn't have internet access, so we need to fetch URLs+ and convert them to base64 data URIs.++ Args:+ url: The URL to convert++ Returns:+ Base64 data URI string+ """+ verbose_logger.debug(f"Vertex AI OCR: Converting URL to base64 data URI (async): {url}")++ # Fetch and convert to base64 data URI asynchronously+ # async_convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..."+ data_uri = await async_convert_url_to_base64(url=url)++ verbose_logger.debug(f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})")++ return data_uri++ def transform_ocr_request(+ self,+ model: str,+ document: DocumentType,+ optional_params: dict,+ headers: dict,+ **kwargs,+ ) -> OCRRequestData:+ """+ Transform OCR request for Vertex AI, converting URLs to base64 data URIs (sync).++ Vertex AI OCR doesn't have internet access, so we automatically fetch+ any URLs and convert them to base64 data URIs synchronously.++ Args:+ model: Model name+ document: Document dict from user+ optional_params: Already mapped optional parameters+ headers: Request headers+ **kwargs: Additional arguments++ Returns:+ OCRRequestData with JSON data+ """+ verbose_logger.debug("Vertex AI OCR transform_ocr_request (sync) called")++ if not isinstance(document, dict):+ raise ValueError(f"Expected document dict, got {type(document)}")++ # Check if we need to convert URL to base64+ doc_type = document.get("type")+ transformed_document = document.copy()++ if doc_type == "document_url":+ document_url = document.get("document_url", "")+ # If it's not already a data URI, convert it+ if document_url and not document_url.startswith("data:"):+ verbose_logger.debug(+ "Vertex AI OCR: Converting document URL to base64 data URI (sync)"+ )+ data_uri = self._convert_url_to_data_uri_sync(url=document_url)+ transformed_document["document_url"] = data_uri+ elif doc_type == "image_url":+ image_url = document.get("image_url", "")+ # If it's not already a data URI, convert it+ if image_url and not image_url.startswith("data:"):+ verbose_logger.debug(+ "Vertex AI OCR: Converting image URL to base64 data URI (sync)"+ )+ data_uri = self._convert_url_to_data_uri_sync(url=image_url)+ transformed_document["image_url"] = data_uri++ # Call parent's transform to build the request+ return super().transform_ocr_request(+ model=model,+ document=transformed_document,+ optional_params=optional_params,+ headers=headers,+ **kwargs,+ )++ async def async_transform_ocr_request(+ self,+ model: str,+ document: DocumentType,+ optional_params: dict,+ headers: dict,+ **kwargs,+ ) -> OCRRequestData:+ """+ Transform OCR request for Vertex AI, converting URLs to base64 data URIs (async).++ Vertex AI OCR doesn't have internet access, so we automatically fetch+ any URLs and convert them to base64 data URIs asynchronously.++ Args:+ model: Model name+ document: Document dict from user+ optional_params: Already mapped optional parameters+ headers: Request headers+ **kwargs: Additional arguments++ Returns:+ OCRRequestData with JSON data+ """+ verbose_logger.debug(f"Vertex AI OCR async_transform_ocr_request - model: {model}")++ if not isinstance(document, dict):+ raise ValueError(f"Expected document dict, got {type(document)}")++ # Check if we need to convert URL to base64+ doc_type = document.get("type")+ transformed_document = document.copy()++ if doc_type == "document_url":+ document_url = document.get("document_url", "")+ # If it's not already a data URI, convert it+ if document_url and not document_url.startswith("data:"):+ verbose_logger.debug(+ "Vertex AI OCR: Converting document URL to base64 data URI (async)"+ )+ data_uri = await self._convert_url_to_data_uri_async(url=document_url)+ transformed_document["document_url"] = data_uri+ elif doc_type == "image_url":+ image_url = document.get("image_url", "")+ # If it's not already a data URI, convert it+ if image_url and not image_url.startswith("data:"):+ verbose_logger.debug(+ "Vertex AI OCR: Converting image URL to base64 data URI (async)"+ )+ data_uri = await self._convert_url_to_data_uri_async(url=image_url)+ transformed_document["image_url"] = data_uri++ # Call parent's transform to build the request+ return super().transform_ocr_request(+ model=model,+ document=transformed_document,+ optional_params=optional_params,+ headers=headers,+ **kwargs,+ )+diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.pyindex 8f7c846bd7d..54608991595 100644--- a/litellm/llms/vertex_ai/vertex_llm_base.py+++ b/litellm/llms/vertex_ai/vertex_llm_base.py@@ -625,3 +625,66 @@ class VertexBase:or get_secret_str("VERTEXAI_LOCATION")or get_secret_str("VERTEX_LOCATION"))++ @staticmethod+ def safe_get_vertex_ai_project(litellm_params: dict) -> Optional[str]:+ """+ Safely get Vertex AI project without mutating the litellm_params dict.++ Unlike get_vertex_ai_project(), this does NOT pop values from the dict,+ making it safe to call multiple times with the same litellm_params.++ Args:+ litellm_params: Dictionary containing Vertex AI parameters++ Returns:+ Vertex AI project ID or None+ """+ return (+ litellm_params.get("vertex_project")+ or litellm_params.get("vertex_ai_project")+ or litellm.vertex_project+ or get_secret_str("VERTEXAI_PROJECT")+ )++ @staticmethod+ def safe_get_vertex_ai_credentials(litellm_params: dict) -> Optional[str]:+ """+ Safely get Vertex AI credentials without mutating the litellm_params dict.++ Unlike get_vertex_ai_credentials(), this does NOT pop values from the dict,+ making it safe to call multiple times with the same litellm_params.++ Args:+ litellm_params: Dictionary containing Vertex AI parameters++ Returns:+ Vertex AI credentials or None+ """+ return (+ litellm_params.get("vertex_credentials")+ or litellm_params.get("vertex_ai_credentials")+ or get_secret_str("VERTEXAI_CREDENTIALS")+ )++ @staticmethod+ def safe_get_vertex_ai_location(litellm_params: dict) -> Optional[str]:+ """+ Safely get Vertex AI location without mutating the litellm_params dict.++ Unlike get_vertex_ai_location(), this does NOT pop values from the dict,+ making it safe to call multiple times with the same litellm_params.++ Args:+ litellm_params: Dictionary containing Vertex AI parameters++ Returns:+ Vertex AI location/region or None+ """+ return (+ litellm_params.get("vertex_location")+ or litellm_params.get("vertex_ai_location")+ or litellm.vertex_location+ or get_secret_str("VERTEXAI_LOCATION")+ or get_secret_str("VERTEX_LOCATION")+ )diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex e20ab6f564d..86af6995c7d 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -18211,15 +18211,6 @@"output_cost_per_token": 2e-07,"supports_tool_choice": true},- "openrouter/nvidia/nemotron-nano-9b-v2:free": {- "input_cost_per_token": 0,- "litellm_provider": "openrouter",- "max_tokens": 128000,- "mode": "chat",- "output_cost_per_token": 0,- "source": "https://openrouter.ai/nvidia/nemotron-nano-9b-v2:free",- "supports_tool_choice": true- },"openrouter/openai/gpt-3.5-turbo": {"input_cost_per_token": 1.5e-06,"litellm_provider": "openrouter",@@ -22910,6 +22901,15 @@"supports_function_calling": true,"supports_tool_choice": true},+ "vertex_ai/mistral-ocr-2505": {+ "litellm_provider": "vertex_ai",+ "mode": "ocr",+ "ocr_cost_per_page": 5e-4,+ "supported_endpoints": [+ "/v1/ocr"+ ],+ "source": "https://cloud.google.com/generative-ai-app-builder/pricing"+ },"vertex_ai/openai/gpt-oss-120b-maas": {"input_cost_per_token": 1.5e-07,"litellm_provider": "vertex_ai-openai_models",@@ -24081,16 +24081,6 @@"1280x720"]},- "openai/container": {- "code_interpreter_cost_per_session": 0.03,- "litellm_provider": "openai",- "mode": "container"- },- "azure/container": {- "code_interpreter_cost_per_session": 0.03,- "litellm_provider": "azure",- "mode": "container"- },"azure/sora-2": {"litellm_provider": "azure","mode": "video_generation",diff --git a/litellm/ocr/main.py b/litellm/ocr/main.pyindex 62172b0fbae..5acab8cbf2c 100644--- a/litellm/ocr/main.py+++ b/litellm/ocr/main.py@@ -14,6 +14,7 @@ from litellm.constants import request_timeoutfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.llms.base_llm.ocr.transformation import BaseOCRConfig, OCRResponsefrom litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler+from litellm.types.router import GenericLiteLLMParamsfrom litellm.utils import ProviderConfigManager, client####### ENVIRONMENT VARIABLES ###################@@ -243,6 +244,9 @@ def ocr(f"OCR call - model: {model}, provider: {custom_llm_provider}")+ # Get litellm params using GenericLiteLLMParams (same as responses API)+ litellm_params = GenericLiteLLMParams(**kwargs)+# Extract OCR-specific parameters from kwargssupported_params = ocr_provider_config.get_supported_ocr_params(model=model)non_default_params = {}@@ -283,10 +287,7 @@ def ocr(aocr=_is_async,headers=extra_headers,provider_config=ocr_provider_config,- litellm_params={- "api_base": api_base,- "api_key": api_key,- },+ litellm_params=dict(litellm_params),)return responsediff --git a/litellm/utils.py b/litellm/utils.pyindex 8a51934181f..c18ecc43781 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -7742,10 +7742,12 @@ class ProviderConfigManager:Get OCR configuration for a given provider."""from litellm.llms.azure_ai.ocr.transformation import AzureAIOCRConfig+ from litellm.llms.vertex_ai.ocr.transformation import VertexAIOCRConfigPROVIDER_TO_CONFIG_MAP = {litellm.LlmProviders.MISTRAL: MistralOCRConfig,litellm.LlmProviders.AZURE_AI: AzureAIOCRConfig,+ litellm.LlmProviders.VERTEX_AI: VertexAIOCRConfig,}config_class = PROVIDER_TO_CONFIG_MAP.get(provider, None)if config_class is None:diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex e20ab6f564d..86af6995c7d 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -18211,15 +18211,6 @@"output_cost_per_token": 2e-07,"supports_tool_choice": true},- "openrouter/nvidia/nemotron-nano-9b-v2:free": {- "input_cost_per_token": 0,- "litellm_provider": "openrouter",- "max_tokens": 128000,- "mode": "chat",- "output_cost_per_token": 0,- "source": "https://openrouter.ai/nvidia/nemotron-nano-9b-v2:free",- "supports_tool_choice": true- },"openrouter/openai/gpt-3.5-turbo": {"input_cost_per_token": 1.5e-06,"litellm_provider": "openrouter",@@ -22910,6 +22901,15 @@"supports_function_calling": true,"supports_tool_choice": true},+ "vertex_ai/mistral-ocr-2505": {+ "litellm_provider": "vertex_ai",+ "mode": "ocr",+ "ocr_cost_per_page": 5e-4,+ "supported_endpoints": [+ "/v1/ocr"+ ],+ "source": "https://cloud.google.com/generative-ai-app-builder/pricing"+ },"vertex_ai/openai/gpt-oss-120b-maas": {"input_cost_per_token": 1.5e-07,"litellm_provider": "vertex_ai-openai_models",@@ -24081,16 +24081,6 @@"1280x720"]},- "openai/container": {- "code_interpreter_cost_per_session": 0.03,- "litellm_provider": "openai",- "mode": "container"- },- "azure/container": {- "code_interpreter_cost_per_session": 0.03,- "litellm_provider": "azure",- "mode": "container"- },"azure/sora-2": {"litellm_provider": "azure","mode": "video_generation",diff --git a/provider_endpoints_support.json b/provider_endpoints_support.jsonindex 40f46d368dc..a1a3f5a2820 100644--- a/provider_endpoints_support.json+++ b/provider_endpoints_support.json@@ -14,7 +14,8 @@"audio_speech": "Supports /audio/speech endpoint","moderations": "Supports /moderations endpoint","batches": "Supports /batches endpoint",- "rerank": "Supports /rerank endpoint"+ "rerank": "Supports /rerank endpoint",+ "ocr": "Supports /ocr endpoint"}}},@@ -192,7 +193,8 @@"audio_speech": true,"moderations": true,"batches": true,- "rerank": false+ "rerank": false,+ "ocr": true}},"azure_text": {@@ -656,7 +658,8 @@"audio_speech": false,"moderations": false,"batches": false,- "rerank": false+ "rerank": false,+ "ocr": true}},"gemini": {@@ -944,7 +947,8 @@"audio_speech": false,"moderations": false,"batches": false,- "rerank": false+ "rerank": false,+ "ocr": true}},"moonshot": {diff --git a/tests/ocr_tests/base_ocr_unit_tests.py b/tests/ocr_tests/base_ocr_unit_tests.pyindex 64da2f044d8..aaa135a4d6b 100644--- a/tests/ocr_tests/base_ocr_unit_tests.py+++ b/tests/ocr_tests/base_ocr_unit_tests.py@@ -32,8 +32,13 @@ class BaseOCRTest(ABC):"""Fixture to handle rate limit errors for all test methods"""try:yield- except litellm.RateLimitError:- pytest.skip("Rate limit exceeded")+ except litellm.RateLimitError as e:+ # Check if it's a quota exceeded error+ error_msg = str(e)+ if "Quota exceeded" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:+ pytest.skip(f"Quota exceeded - {error_msg}")+ else:+ pytest.skip(f"Rate limit exceeded - {error_msg}")except litellm.InternalServerError:pytest.skip("Model is overloaded")@@ -112,6 +117,9 @@ class BaseOCRTest(ABC):assert response_cost > 0, "Response cost should be greater than 0"print("response_cost=", response_cost)+ except (litellm.RateLimitError, litellm.InternalServerError):+ # Re-raise these errors so the fixture can handle them+ raiseexcept Exception as e:pytest.fail(f"OCR call failed: {str(e)}")@@ -122,35 +130,42 @@ class BaseOCRTest(ABC):litellm.set_verbose = Truebase_ocr_call_args = self.get_base_ocr_call_args()- response = litellm.ocr(- document={- "type": "document_url",- "document_url": TEST_PDF_URL- },- **base_ocr_call_args,- )-- # Validate response structure- assert hasattr(response, "pages"), "Response should have 'pages' attribute"- assert hasattr(response, "model"), "Response should have 'model' attribute"- assert hasattr(response, "object"), "Response should have 'object' attribute"- assert hasattr(response, "usage_info"), "Response should have 'usage_info' attribute"-- assert isinstance(response.pages, list), "pages should be a list"- assert len(response.pages) > 0, "Should have at least one page"- assert response.object == "ocr", "object should be 'ocr'"-- # Validate first page structure- first_page = response.pages[0]- assert hasattr(first_page, "index"), "Page should have 'index' attribute"- assert hasattr(first_page, "markdown"), "Page should have 'markdown' attribute"- assert isinstance(first_page.markdown, str), "markdown should be a string"+ try:+ response = litellm.ocr(+ document={+ "type": "document_url",+ "document_url": TEST_PDF_URL+ },+ **base_ocr_call_args,+ )++ # Validate response structure+ assert hasattr(response, "pages"), "Response should have 'pages' attribute"+ assert hasattr(response, "model"), "Response should have 'model' attribute"+ assert hasattr(response, "object"), "Response should have 'object' attribute"+ assert hasattr(response, "usage_info"), "Response should have 'usage_info' attribute"++ assert isinstance(response.pages, list), "pages should be a list"+ assert len(response.pages) > 0, "Should have at least one page"+ assert response.object == "ocr", "object should be 'ocr'"++ # Validate first page structure+ first_page = response.pages[0]+ assert hasattr(first_page, "index"), "Page should have 'index' attribute"+ assert hasattr(first_page, "markdown"), "Page should have 'markdown' attribute"+ assert isinstance(first_page.markdown, str), "markdown should be a string"++ print(f"\nResponse structure validated:")+ print(f" - object: {response.object}")+ print(f" - model: {response.model}")+ print(f" - pages: {len(response.pages)}")+ if response.usage_info:+ print(f" - pages_processed: {response.usage_info.pages_processed}")+ print(f" - doc_size_bytes: {response.usage_info.doc_size_bytes}")- print(f"\nResponse structure validated:")- print(f" - object: {response.object}")- print(f" - model: {response.model}")- print(f" - pages: {len(response.pages)}")- if response.usage_info:- print(f" - pages_processed: {response.usage_info.pages_processed}")- print(f" - doc_size_bytes: {response.usage_info.doc_size_bytes}")+ except (litellm.RateLimitError, litellm.InternalServerError):+ # Re-raise these errors so the fixture can handle them+ raise+ except Exception as e:+ pytest.fail(f"OCR response structure test failed: {str(e)}")diff --git a/tests/ocr_tests/test_ocr_vertex_ai.py b/tests/ocr_tests/test_ocr_vertex_ai.pynew file mode 100644index 00000000000..3118871bca8--- /dev/null+++ b/tests/ocr_tests/test_ocr_vertex_ai.py@@ -0,0 +1,71 @@+"""+Test OCR functionality with Vertex AI Mistral OCR API.++Note: Vertex AI OCR automatically converts URLs to base64 data URIs since+the Vertex AI endpoint doesn't have internet access.+"""+import os+import json+import tempfile+from base_ocr_unit_tests import BaseOCRTest+++def load_vertex_ai_credentials():+ """Load Vertex AI credentials for tests"""+ # Define the path to the vertex_key.json file+ print("loading vertex ai credentials")+ filepath = os.path.dirname(os.path.abspath(__file__))+ vertex_key_path = filepath + "/vertex_key.json"++ # Read the existing content of the file or create an empty dictionary+ try:+ with open(vertex_key_path, "r") as file:+ # Read the file content+ print("Read vertexai file path")+ content = file.read()++ # If the file is empty or not valid JSON, create an empty dictionary+ if not content or not content.strip():+ service_account_key_data = {}+ else:+ # Attempt to load the existing JSON content+ file.seek(0)+ service_account_key_data = json.load(file)+ except FileNotFoundError:+ # If the file doesn't exist, create an empty dictionary+ service_account_key_data = {}++ # Update the service_account_key_data with environment variables+ private_key_id = os.environ.get("VERTEX_AI_PRIVATE_KEY_ID", "")+ private_key = os.environ.get("VERTEX_AI_PRIVATE_KEY", "")+ private_key = private_key.replace("\\n", "\n")+ service_account_key_data["private_key_id"] = private_key_id+ service_account_key_data["private_key"] = private_key++ # Create a temporary file+ with tempfile.NamedTemporaryFile(mode="w+", delete=False) as temp_file:+ # Write the updated content to the temporary files+ json.dump(service_account_key_data, temp_file, indent=2)++ # Export the temporary file as GOOGLE_APPLICATION_CREDENTIALS+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.abspath(temp_file.name)++class TestVertexAIOCR(BaseOCRTest):+ """+ Test class for Vertex AI Mistral OCR functionality.+ Inherits from BaseOCRTest and provides Vertex AI-specific configuration.++ Note: For Vertex AI, LiteLLM will automatically convert URLs to base64 data URIs before+ sending to the API, since Vertex AI OCR endpoint doesn't have internet access.+ """++ def get_base_ocr_call_args(self) -> dict:+ """+ Return the base OCR call args for Vertex AI.+ """+ load_vertex_ai_credentials()+ return {+ "model": "vertex_ai/mistral-ocr-2505",+ "vertex_location": "us-central1",+ }+diff --git a/tests/ocr_tests/vertex_key.json b/tests/ocr_tests/vertex_key.jsonnew file mode 100644index 00000000000..45ca6acc010--- /dev/null+++ b/tests/ocr_tests/vertex_key.json@@ -0,0 +1,13 @@+{+ "type": "service_account",+ "project_id": "pathrise-convert-1606954137718",+ "private_key_id": "",+ "private_key": "",+ "client_email": "[email protected]",+ "client_id": "109577393201924326488",+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",+ "token_uri": "https://oauth2.googleapis.com/token",+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ci-cd-723%40pathrise-convert-1606954137718.iam.gserviceaccount.com",+ "universe_domain": "googleapis.com"+}