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
Add support for ocr for vertex ai deepseek model
Sameer Kankute858879919c92
diff --git a/docs/my-website/docs/providers/vertex_ocr.md b/docs/my-website/docs/providers/vertex_ocr.mdindex 4e3d4b0a063..9ff22a03775 100644--- a/docs/my-website/docs/providers/vertex_ocr.md+++ b/docs/my-website/docs/providers/vertex_ocr.md@@ -140,7 +140,7 @@ with open("document.pdf", "rb") as f:pdf_base64 = base64.b64encode(f.read()).decode()response = litellm.ocr(- model="vertex_ai/mistral-ocr-2505",+ model="vertex_ai/mistral-ocr-2505", # This doesn't work for deepseekdocument={"type": "document_url","document_url": f"data:application/pdf;base64,{pdf_base64}"@@ -219,7 +219,7 @@ 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.+Vertex AI Mistral 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@@ -227,11 +227,14 @@ Mistral OCR is available in multiple regions. Specify `vertex_location` to use a- `us-central1` (default)- `europe-west1`- `asia-southeast1`++Deepseek OCR is only available in global region.:::## Supported Models- `mistral-ocr-2505` - Latest Mistral OCR model on Vertex AI+- `deepseek-ocr-maas` - Lates Deepseek OCR model on Vertex AIUse the Vertex AI provider prefix: `vertex_ai/<model-name>`diff --git a/litellm/llms/vertex_ai/ocr/common_utils.py b/litellm/llms/vertex_ai/ocr/common_utils.pynew file mode 100644index 00000000000..8a11b0395d8--- /dev/null+++ b/litellm/llms/vertex_ai/ocr/common_utils.py@@ -0,0 +1,43 @@+"""+Common utilities for Vertex AI OCR providers.++This module provides routing logic to determine which OCR configuration to use+based on the model name.+"""++from typing import TYPE_CHECKING, Optional++from litellm._logging import verbose_logger++if TYPE_CHECKING:+ from litellm.llms.base_llm.ocr.transformation import BaseOCRConfig+++def get_vertex_ai_ocr_config(model: str) -> Optional["BaseOCRConfig"]:+ """+ Determine which Vertex AI OCR configuration to use based on the model name.++ Vertex AI supports multiple OCR services:+ - Vertex AI OCR: vertex_ai/<model>++ Args:+ model: The model name (e.g., "vertex_ai/ocr/<model>")++ Returns:+ OCR configuration instance for the specified model++ Examples:+ >>> get_vertex_ai_ocr_config("vertex_ai/deepseek-ai/deepseek-ocr-maas")+ <VertexAIDeepSeekOCRConfig object>++ >>> get_vertex_ai_ocr_config("vertex_ai/ocr/mistral-ocr-maas")+ <VertexAIOCRConfig object>+ """+ from litellm.llms.vertex_ai.ocr.deepseek_transformation import (+ VertexAIDeepSeekOCRConfig,+ )+ from litellm.llms.vertex_ai.ocr.transformation import VertexAIOCRConfig+ if "deepseek" in model:+ return VertexAIDeepSeekOCRConfig()+ return VertexAIOCRConfig()+diff --git a/litellm/llms/vertex_ai/ocr/deepseek_transformation.py b/litellm/llms/vertex_ai/ocr/deepseek_transformation.pynew file mode 100644index 00000000000..db7f824a354--- /dev/null+++ b/litellm/llms/vertex_ai/ocr/deepseek_transformation.py@@ -0,0 +1,394 @@+"""+Vertex AI DeepSeek OCR transformation implementation.+"""+import json+from typing import TYPE_CHECKING, Any, Dict, Optional++import httpx++from litellm._logging import verbose_logger+from litellm.llms.base_llm.ocr.transformation import (+ BaseOCRConfig,+ DocumentType,+ OCRPage,+ OCRRequestData,+ OCRResponse,+ OCRUsageInfo,+)+from litellm.llms.vertex_ai.vertex_llm_base import VertexBase++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+else:+ LiteLLMLoggingObj = Any+++class VertexAIDeepSeekOCRConfig(BaseOCRConfig):+ """+ Vertex AI DeepSeek OCR transformation configuration.++ Vertex AI DeepSeek OCR uses the chat completion API format through the openapi endpoint.+ This transformation converts OCR requests to chat completion format and vice versa.+ """++ 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 DeepSeek OCR endpoint.++ Vertex AI endpoint format:+ https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/openapi/chat/completions++ Args:+ api_base: Vertex AI API base URL (optional)+ model: Model name (e.g., "deepseek-ai/deepseek-ocr-maas")+ 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://aiplatform.googleapis.com"++ # Ensure no trailing slash+ api_base = api_base.rstrip("/")++ # Vertex AI DeepSeek OCR endpoint format+ # Format: https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/{region}/endpoints/openapi/chat/completions+ return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/endpoints/openapi/chat/completions"++ def transform_ocr_request(+ self,+ model: str,+ document: DocumentType,+ optional_params: dict,+ headers: dict,+ **kwargs,+ ) -> OCRRequestData:+ """+ Transform OCR request to chat completion format for Vertex AI DeepSeek OCR.++ Converts OCR document format to chat completion messages format:+ - Input: {"type": "image_url", "image_url": "gs://..."}+ - Output: {"model": "deepseek-ai/deepseek-ocr-maas", "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": "gs://..."}]}]}++ Args:+ model: Model name (e.g., "deepseek-ai/deepseek-ocr-maas")+ document: Document dict from user (Mistral OCR format)+ optional_params: Already mapped optional parameters+ headers: Request headers+ **kwargs: Additional arguments++ Returns:+ OCRRequestData with JSON data in chat completion format+ """+ verbose_logger.debug("Vertex AI DeepSeek OCR transform_ocr_request (sync) called")++ if not isinstance(document, dict):+ raise ValueError(f"Expected document dict, got {type(document)}")++ # Extract document type and URL+ doc_type = document.get("type")+ image_url = None+ document_url = None++ if doc_type == "image_url":+ image_url = document.get("image_url", "")+ elif doc_type == "document_url":+ document_url = document.get("document_url", "")+ else:+ raise ValueError(f"Unsupported document type: {doc_type}. Expected 'image_url' or 'document_url'")++ # Build chat completion message content+ content_item = {}+ if image_url:+ content_item = {+ "type": "image_url",+ "image_url": image_url+ }+ elif document_url:+ # For document URLs, we use image_url type as well (Vertex AI supports both)+ content_item = {+ "type": "image_url",+ "image_url": document_url+ }++ # Build chat completion request+ data = {+ "model": "deepseek-ai/" + model,+ "messages": [+ {+ "role": "user",+ "content": [content_item]+ }+ ]+ }++ # Add optional parameters (stream, temperature, etc.)+ # Filter out OCR-specific params that don't apply to chat completion+ chat_completion_params = {}+ for key, value in optional_params.items():+ # Include common chat completion params+ if key in ["stream", "temperature", "max_tokens", "top_p", "n", "stop"]:+ chat_completion_params[key] = value++ data.update(chat_completion_params)++ verbose_logger.debug(f"Vertex AI DeepSeek OCR: Transformed request to chat completion format")++ return OCRRequestData(data=data, files=None)++ async def async_transform_ocr_request(+ self,+ model: str,+ document: DocumentType,+ optional_params: dict,+ headers: dict,+ **kwargs,+ ) -> OCRRequestData:+ """+ Transform OCR request to chat completion format for Vertex AI DeepSeek OCR (async).++ Same as sync version - no async-specific logic needed.++ 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 in chat completion format+ """+ return self.transform_ocr_request(+ model=model,+ document=document,+ optional_params=optional_params,+ headers=headers,+ **kwargs,+ )++ def transform_ocr_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ **kwargs,+ ) -> OCRResponse:+ """+ Transform chat completion response to OCR format.++ Vertex AI DeepSeek OCR returns chat completion format:+ {+ "id": "...",+ "object": "chat.completion",+ "choices": [{+ "message": {+ "role": "assistant",+ "content": "<OCR result as JSON string or markdown>"+ }+ }],+ "usage": {...}+ }++ We need to extract the content and convert it to OCRResponse format.++ Args:+ model: Model name+ raw_response: Raw HTTP response from Vertex AI+ logging_obj: Logging object+ **kwargs: Additional arguments++ Returns:+ OCRResponse in standard format+ """+ verbose_logger.debug("Vertex AI DeepSeek OCR transform_ocr_response called")+ verbose_logger.debug(f"Raw response: {raw_response.text}")++ try:+ response_json = raw_response.json()++ # Extract content from chat completion response+ choices = response_json.get("choices", [])+ if not choices:+ raise ValueError("No choices in chat completion response")++ message = choices[0].get("message", {})+ content = message.get("content", "")++ if not content:+ raise ValueError("No content in chat completion response")++ # Try to parse content as JSON (OCR result might be JSON string)+ ocr_data = None+ try:+ # If content is a JSON string, parse it+ if isinstance(content, str) and content.strip().startswith("{"):+ ocr_data = json.loads(content)+ elif isinstance(content, dict):+ ocr_data = content+ else:+ # If content is markdown text, create a single page with the markdown+ ocr_data = {+ "pages": [+ {+ "index": 0,+ "markdown": content+ }+ ],+ "model": model,+ "usage_info": response_json.get("usage", {})+ }+ except json.JSONDecodeError:+ # If JSON parsing fails, treat content as markdown+ ocr_data = {+ "pages": [+ {+ "index": 0,+ "markdown": content+ }+ ],+ "model": model,+ "usage_info": response_json.get("usage", {})+ }++ # Ensure we have the expected structure+ if "pages" not in ocr_data:+ # If OCR data doesn't have pages, wrap the content in a page+ ocr_data = {+ "pages": [+ {+ "index": 0,+ "markdown": content if isinstance(content, str) else json.dumps(content)+ }+ ],+ "model": ocr_data.get("model", model),+ "usage_info": ocr_data.get("usage_info", response_json.get("usage", {}))+ }++ # Convert usage info if present+ usage_info = None+ if "usage_info" in ocr_data:+ usage_dict = ocr_data["usage_info"]+ if isinstance(usage_dict, dict):+ usage_info = OCRUsageInfo(**usage_dict)++ # Build OCRResponse+ pages = []+ for page_data in ocr_data.get("pages", []):+ # Ensure page has required fields+ if isinstance(page_data, dict):+ page = OCRPage(+ index=page_data.get("index", 0),+ markdown=page_data.get("markdown", ""),+ images=page_data.get("images"),+ dimensions=page_data.get("dimensions")+ )+ pages.append(page)++ if not pages:+ # Create a default page if none exist+ pages = [OCRPage(index=0, markdown=content if isinstance(content, str) else "")]++ return OCRResponse(+ pages=pages,+ model=ocr_data.get("model", model),+ document_annotation=ocr_data.get("document_annotation"),+ usage_info=usage_info,+ object="ocr",+ )++ except Exception as e:+ verbose_logger.error(f"Error parsing Vertex AI DeepSeek OCR response: {e}")+ raise e++ async def async_transform_ocr_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ **kwargs,+ ) -> OCRResponse:+ """+ Async transform chat completion response to OCR format.++ Same as sync version - no async-specific logic needed.++ Args:+ model: Model name+ raw_response: Raw HTTP response+ logging_obj: Logging object+ **kwargs: Additional arguments++ Returns:+ OCRResponse in standard format+ """+ return self.transform_ocr_response(+ model=model,+ raw_response=raw_response,+ logging_obj=logging_obj,+ **kwargs,+ )+diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 2af548ce07e..41af219f6c6 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -27111,6 +27111,14 @@],"source": "https://cloud.google.com/generative-ai-app-builder/pricing"},+ "vertex_ai/deepseek-ai/deepseek-ocr-maas": {+ "litellm_provider": "vertex_ai",+ "mode": "ocr",+ "input_cost_per_token": 3e-07,+ "output_cost_per_token": 1.2e-06,+ "ocr_cost_per_page": 3e-04,+ "source": "https://cloud.google.com/vertex-ai/pricing"+ },"vertex_ai/openai/gpt-oss-120b-maas": {"input_cost_per_token": 1.5e-07,"litellm_provider": "vertex_ai-openai_models",diff --git a/litellm/utils.py b/litellm/utils.pyindex e22109712f7..ac9c0fa5c70 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -7932,9 +7932,13 @@ class ProviderConfigManager:return get_azure_ai_ocr_config(model=model)+ if provider == litellm.LlmProviders.VERTEX_AI:+ from litellm.llms.vertex_ai.ocr.common_utils import get_vertex_ai_ocr_config++ return get_vertex_ai_ocr_config(model=model)+PROVIDER_TO_CONFIG_MAP = {litellm.LlmProviders.MISTRAL: MistralOCRConfig,- 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 2af548ce07e..41af219f6c6 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -27111,6 +27111,14 @@],"source": "https://cloud.google.com/generative-ai-app-builder/pricing"},+ "vertex_ai/deepseek-ai/deepseek-ocr-maas": {+ "litellm_provider": "vertex_ai",+ "mode": "ocr",+ "input_cost_per_token": 3e-07,+ "output_cost_per_token": 1.2e-06,+ "ocr_cost_per_page": 3e-04,+ "source": "https://cloud.google.com/vertex-ai/pricing"+ },"vertex_ai/openai/gpt-oss-120b-maas": {"input_cost_per_token": 1.5e-07,"litellm_provider": "vertex_ai-openai_models",diff --git a/proxy_server_config.yaml b/proxy_server_config.yamlindex df3a08a143b..5ea8e316c5d 100644--- a/proxy_server_config.yaml+++ b/proxy_server_config.yaml@@ -1,4 +1,8 @@model_list:+ - model_name: deepseek-v3p2+ litellm_params:+ model: fireworks_ai/accounts/fireworks/models/deepseek-v3p2+ api_key: "os.environ/FIREWORKS_AI_API_KEY"- model_name: gpt-3.5-turbo-end-user-testlitellm_params:model: gpt-3.5-turbodiff --git a/tests/ocr_tests/test_ocr_vertex_ai.py b/tests/ocr_tests/test_ocr_vertex_ai.pyindex 3118871bca8..1c88736bd34 100644--- a/tests/ocr_tests/test_ocr_vertex_ai.py+++ b/tests/ocr_tests/test_ocr_vertex_ai.py@@ -1,5 +1,5 @@"""-Test OCR functionality with Vertex AI Mistral OCR API.+Test OCR functionality with Vertex AI OCR APIs (Mistral and DeepSeek).Note: Vertex AI OCR automatically converts URLs to base64 data URIs sincethe Vertex AI endpoint doesn't have internet access.@@ -50,7 +50,8 @@ def load_vertex_ai_credentials():# Export the temporary file as GOOGLE_APPLICATION_CREDENTIALSos.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.abspath(temp_file.name)-class TestVertexAIOCR(BaseOCRTest):++class TestVertexAIMistralOCR(BaseOCRTest):"""Test class for Vertex AI Mistral OCR functionality.Inherits from BaseOCRTest and provides Vertex AI-specific configuration.@@ -61,7 +62,7 @@ class TestVertexAIOCR(BaseOCRTest):def get_base_ocr_call_args(self) -> dict:"""- Return the base OCR call args for Vertex AI.+ Return the base OCR call args for Vertex AI Mistral OCR."""load_vertex_ai_credentials()return {@@ -69,3 +70,46 @@ class TestVertexAIOCR(BaseOCRTest):"vertex_location": "us-central1",}++class TestVertexAIDeepSeekOCR(BaseOCRTest):+ """+ Test class for Vertex AI DeepSeek OCR functionality.+ Inherits from BaseOCRTest and provides Vertex AI-specific configuration.++ Note: DeepSeek OCR uses the chat completion API format through the openapi endpoint.+ """++ def get_base_ocr_call_args(self) -> dict:+ """+ Return the base OCR call args for Vertex AI DeepSeek OCR.+ """+ load_vertex_ai_credentials()+ return {+ "model": "vertex_ai/deepseek-ai/deepseek-ocr-maas",+ "vertex_location": "us-central1",+ }+++def test_vertex_ai_ocr_routing():+ """+ Test that Vertex AI OCR routing correctly selects the right config based on model name.+ """+ from litellm.llms.vertex_ai.ocr.common_utils import get_vertex_ai_ocr_config+ from litellm.llms.vertex_ai.ocr.deepseek_transformation import VertexAIDeepSeekOCRConfig+ from litellm.llms.vertex_ai.ocr.transformation import VertexAIOCRConfig++ # Test DeepSeek OCR routing+ deepseek_config = get_vertex_ai_ocr_config("vertex_ai/deepseek-ai/deepseek-ocr-maas")+ assert isinstance(deepseek_config, VertexAIDeepSeekOCRConfig), \+ "DeepSeek model should route to VertexAIDeepSeekOCRConfig"++ # Test Mistral OCR routing (should use default VertexAIOCRConfig)+ mistral_config = get_vertex_ai_ocr_config("vertex_ai/mistral-ocr-2505")+ assert isinstance(mistral_config, VertexAIOCRConfig), \+ "Mistral model should route to VertexAIOCRConfig"++ # Test other DeepSeek variants+ deepseek_variant = get_vertex_ai_ocr_config("vertex_ai/deepseek-ocr-maas")+ assert isinstance(deepseek_variant, VertexAIDeepSeekOCRConfig), \+ "DeepSeek variant should route to VertexAIDeepSeekOCRConfig"+