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(JinaAI): support multimodal embedding models (#13181)
zjx2092c525ddfed7
diff --git a/litellm/litellm_core_utils/get_supported_openai_params.py b/litellm/litellm_core_utils/get_supported_openai_params.pyindex f1901fa2ce9..b2a2c364240 100644--- a/litellm/litellm_core_utils/get_supported_openai_params.py+++ b/litellm/litellm_core_utils/get_supported_openai_params.py@@ -146,7 +146,9 @@ def get_supported_openai_params( # noqa: PLR0915return litellm.HuggingFaceChatConfig().get_supported_openai_params(model=model)elif custom_llm_provider == "jina_ai":if request_type == "embeddings":- return litellm.JinaAIEmbeddingConfig().get_supported_openai_params()+ return litellm.JinaAIEmbeddingConfig().get_supported_openai_params(+ model=model+ )elif custom_llm_provider == "together_ai":return litellm.TogetherAIConfig().get_supported_openai_params(model=model)elif custom_llm_provider == "databricks":diff --git a/litellm/llms/jina_ai/common_utils.py b/litellm/llms/jina_ai/common_utils.pynew file mode 100644index 00000000000..cd9fd402afb--- /dev/null+++ b/litellm/llms/jina_ai/common_utils.py@@ -0,0 +1,6 @@+from litellm.llms.base_llm.chat.transformation import BaseLLMException+++class JinaAIError(BaseLLMException):+ def __init__(self, status_code, message):+ super().__init__(status_code=status_code, message=message)diff --git a/litellm/llms/jina_ai/embedding/transformation.py b/litellm/llms/jina_ai/embedding/transformation.pyindex 5263be900fa..7a634903005 100644--- a/litellm/llms/jina_ai/embedding/transformation.py+++ b/litellm/llms/jina_ai/embedding/transformation.py@@ -1,5 +1,5 @@"""-Transformation logic from OpenAI /v1/embeddings format to Jina AI's `/v1/embeddings` format.+Transformation logic from OpenAI /v1/embeddings format to Jina AI's `/v1/embeddings` format.Why separate file? Make it easy to see how transformation works@@ -7,13 +7,23 @@ Docs - https://jina.ai/embeddings/"""import types-from typing import List, Optional, Tuple+from typing import List, Optional, Tuple, Union, cast++import httpxfrom litellm import LlmProvidersfrom litellm.secret_managers.main import get_secret_str+from litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.llms.base_llm import BaseEmbeddingConfig+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.types.llms.openai import AllEmbeddingInputValues, AllMessageValues+from litellm.types.utils import EmbeddingResponse+from litellm.utils import is_base64_encoded++from ..common_utils import JinaAIError-class JinaAIEmbeddingConfig:+class JinaAIEmbeddingConfig(BaseEmbeddingConfig):"""Reference: https://jina.ai/embeddings/"""@@ -44,11 +54,15 @@ class JinaAIEmbeddingConfig:and v is not None}- def get_supported_openai_params(self) -> List[str]:+ def get_supported_openai_params(self, model: str) -> List[str]:return ["dimensions"]def map_openai_params(- self, non_default_params: dict, optional_params: dict+ self,+ non_default_params: dict,+ optional_params: dict,+ model: str,+ drop_params: bool,) -> dict:if "dimensions" in non_default_params:optional_params["dimensions"] = non_default_params["dimensions"]@@ -76,3 +90,88 @@ class JinaAIEmbeddingConfig:or get_secret_str("JINA_AI_TOKEN"))return LlmProviders.JINA_AI.value, api_base, dynamic_api_key++ def get_complete_url(+ self,+ api_base: Optional[str],+ api_key: Optional[str],+ model: str,+ optional_params: dict,+ litellm_params: dict,+ stream: Optional[bool] = None,+ ) -> str:+ return (+ f"{api_base}/embeddings"+ if api_base+ else "https://api.jina.ai/v1/embeddings"+ )++ def transform_embedding_request(+ self,+ model: str,+ input: AllEmbeddingInputValues,+ optional_params: dict,+ headers: dict,+ ) -> dict:+ data = {"model": model, **optional_params}+ input = cast(List[str], input) if isinstance(input, List) else [input]+ if any((is_base64_encoded(x) for x in input)):+ transformed_input = []+ for value in input:+ if isinstance(value, str):+ if is_base64_encoded(value):+ img_data = value.split(",")[1]+ transformed_input.append({"image": img_data})+ else:+ transformed_input.append({"text": value})+ data["input"] = transformed_input+ else:+ data["input"] = input+ return data++ def transform_embedding_response(+ self,+ model: str,+ raw_response: httpx.Response,+ model_response: EmbeddingResponse,+ logging_obj: LiteLLMLoggingObj,+ api_key: Optional[str],+ request_data: dict,+ optional_params: dict,+ litellm_params: dict,+ ) -> EmbeddingResponse:+ response_json = raw_response.json()+ ## LOGGING+ logging_obj.post_call(+ input=input,+ api_key=api_key,+ additional_args={"complete_input_dict": request_data},+ original_response=response_json,+ )+ return EmbeddingResponse(**response_json)++ def validate_environment(+ self,+ headers: dict,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ ) -> dict:+ default_headers = {+ "Content-Type": "application/json",+ }+ if api_key:+ default_headers["Authorization"] = f"Bearer {api_key}"+ headers = {**default_headers, **headers}+ return headers++ def get_error_class(+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]+ ) -> BaseLLMException:+ return JinaAIError(+ status_code=status_code,+ message=error_message,+ )diff --git a/litellm/main.py b/litellm/main.pyindex 7762e178f63..6bedf8f7ea5 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -3902,7 +3902,6 @@ def embedding( # noqa: PLR0915)elif (custom_llm_provider == "openai_like"- or custom_llm_provider == "jina_ai"or custom_llm_provider == "hosted_vllm"or custom_llm_provider == "llamafile"or custom_llm_provider == "lm_studio"@@ -4329,6 +4328,25 @@ def embedding( # noqa: PLR0915client=client,aembedding=aembedding,)+ elif custom_llm_provider == "jina_ai":+ if isinstance(input, str):+ transformed_input = [input]+ else:+ transformed_input = input+ response = base_llm_http_handler.embedding(+ model=model,+ input=transformed_input,+ custom_llm_provider=custom_llm_provider,+ api_base=api_base,+ api_key=api_key,+ logging_obj=logging,+ timeout=timeout,+ model_response=EmbeddingResponse(),+ optional_params=optional_params,+ litellm_params={},+ client=client,+ aembedding=aembedding,+ )elif custom_llm_provider in litellm._custom_providers:custom_handler: Optional[CustomLLM] = Nonefor item in litellm.custom_provider_map:diff --git a/litellm/utils.py b/litellm/utils.pyindex 36910740e63..ffd8bee382e 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -2790,7 +2790,10 @@ def get_optional_params_embeddings( # noqa: PLR0915)_check_valid_arg(supported_params=supported_params)optional_params = litellm.JinaAIEmbeddingConfig().map_openai_params(- non_default_params=non_default_params, optional_params={}+ non_default_params=non_default_params,+ optional_params={},+ model=model,+ drop_params=drop_params if drop_params is not None else False,)elif custom_llm_provider == "voyage":supported_params = get_supported_openai_params(@@ -6955,6 +6958,12 @@ class ProviderConfigManager:from litellm.llms.cohere.embed.transformation import CohereEmbeddingConfigreturn CohereEmbeddingConfig()+ elif litellm.LlmProviders.JINA_AI == provider:+ from litellm.llms.jina_ai.embedding.transformation import (+ JinaAIEmbeddingConfig,+ )++ return JinaAIEmbeddingConfig()return None@staticmethoddiff --git a/tests/local_testing/test_embedding.py b/tests/local_testing/test_embedding.pyindex 72f057bc60d..06f8346994f 100644--- a/tests/local_testing/test_embedding.py+++ b/tests/local_testing/test_embedding.py@@ -1187,3 +1187,93 @@ async def test_embedding_with_extra_headers(sync_mode):mock_post.assert_called_once()assert "my-test-param" in mock_post.call_args.kwargs["headers"]+++ "input_data, expected_payload_input",+ [+ # Case 1: Input with only text strings+ (+ ["hello world", "foo bar"],+ ["hello world", "foo bar"],+ ),+ # Case 2: Input with a mix of text and a base64 encoded image+ (+ [+ "A picture of a cat",+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",+ ],+ [+ {"text": "A picture of a cat"},+ {+ "image": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+ },+ ],+ ),+ # Case 3: Input with only a base64 encoded image+ (+ [+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+ ],+ [+ {+ "image": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+ }+ ],+ ),+ ],+)+def test_jina_ai_img_embeddings(input_data, expected_payload_input):+ """+ Tests the input transformation logic for Jina AI embeddings using mocks.++ This test verifies that when litellm.embedding is called with a jina_ai model,+ the 'input' field in the request payload is formatted correctly based on whether+ the input contains text or base64 encoded images.+ """+ # We patch the `post` method of the HTTPHandler. This intercepts the network+ # request before it's actually sent.+ with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:+ # Configure the mock to return a successful, minimal valid response.+ # This prevents litellm from raising an error when processing the response.+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "object": "list",+ "data": [+ {+ "object": "embedding",+ "index": 0,+ "embedding": [0.1] * 768, # Dummy embedding vector+ }+ ],+ "model": "jina-embeddings-v4",+ }+ mock_post.return_value = mock_response++ # Call the function we want to test+ try:+ litellm.embedding(+ model="jina_ai/jina-embeddings-v4", input=input_data+ )+ except Exception as e:+ pytest.fail(+ f"litellm.embedding call failed with an unexpected exception: {e}"+ )++ # --- Assertions ---+ # 1. Check that our mock `post` method was called exactly once.+ mock_post.assert_called_once()++ # 2. Extract the keyword arguments passed to the mock call.+ # The request payload is in the 'data' keyword argument.+ kwargs = mock_post.call_args.kwargs+ assert "data" in kwargs++ # 3. Parse the JSON payload string into a Python dictionary.+ sent_data = json.loads(kwargs["data"])++ # 4. This is the core of our test:+ # Assert that the 'input' field in the payload matches our expectation.+ assert "input" in sent_data+ assert sent_data["input"] == expected_payload_inputdiff --git a/tests/test_litellm/llms/jina_ai/embedding/test_jina_embedding_transformation.py b/tests/test_litellm/llms/jina_ai/embedding/test_jina_embedding_transformation.pynew file mode 100644index 00000000000..715d12043d0--- /dev/null+++ b/tests/test_litellm/llms/jina_ai/embedding/test_jina_embedding_transformation.py@@ -0,0 +1,88 @@+import os+import sys+from unittest.mock import MagicMock++sys.path.insert(+ 0, os.path.abspath("../../../../../..")+) # Adds the parent directory to the system path++from litellm.llms.jina_ai.embedding.transformation import JinaAIEmbeddingConfig+++class TestJinaAIEmbeddingTransform:+ def setup_method(self):+ self.config = JinaAIEmbeddingConfig()+ self.model = "jina-embeddings-v2-base-en"+ self.logging_obj = MagicMock()++ def test_map_openai_params(self):+ """Test that 'dimensions' parameter is correctly mapped"""+ test_params = {"dimensions": 1024}+ result = self.config.map_openai_params(+ non_default_params=test_params,+ optional_params={},+ model=self.model,+ drop_params=False,+ )+ assert result == {"dimensions": 1024}++ def test_transform_embedding_request_text_input(self):+ """Test transformation of a standard text embedding request"""+ input_data = ["hello world", "hello world again"]+ result = self.config.transform_embedding_request(+ model=self.model,+ input=input_data,+ optional_params={},+ headers={},+ )+ expected_result = {+ "model": self.model,+ "input": input_data,+ }+ assert result == expected_result++ def test_transform_embedding_request_image_input(self):+ """Test transformation of an image embedding request"""+ # a fake base64 string for testing purposes+ input_data = [+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+ ]+ result = self.config.transform_embedding_request(+ model=self.model,+ input=input_data,+ optional_params={},+ headers={},+ )+ expected_input = [+ {+ "image": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+ }+ ]+ expected_result = {+ "model": self.model,+ "input": expected_input,+ }+ assert result == expected_result++ def test_transform_embedding_request_mixed_input(self):+ """Test transformation of a mixed text and image embedding request"""+ # a fake base64 string for testing purposes+ base64_str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+ input_data = ["hello world", base64_str]+ result = self.config.transform_embedding_request(+ model=self.model,+ input=input_data,+ optional_params={},+ headers={},+ )+ expected_input = [+ {"text": "hello world"},+ {+ "image": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+ },+ ]+ expected_result = {+ "model": self.model,+ "input": expected_input,+ }+ assert result == expected_result