Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: add Jina AI embedding provider (#245)

Han Xiaoea2a508a9cd9
diff --git a/README.md b/README.md
index ccd7f1d6f..bed8fb71a 100644
--- a/README.md
+++ b/README.md
@@ -227,7 +227,7 @@ Create a configuration file `~/.openviking/ov.conf`:
}
```
-> **Note**: For embedding models, currently only `volcengine` (Doubao) and `openai` providers are supported. For VLM models, we support multiple providers including volcengine, openai, deepseek, anthropic, gemini, moonshot, zhipu, dashscope, minimax, and more.
+> **Note**: For embedding models, currently `volcengine` (Doubao), `openai`, and `jina` providers are supported. For VLM models, we support multiple providers including volcengine, openai, deepseek, anthropic, gemini, moonshot, zhipu, dashscope, minimax, and more.
#### Configuration Examples
diff --git a/README_CN.md b/README_CN.md
index c09354ed6..b2f8875ff 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -91,7 +91,7 @@ OpenViking 支持多种模型服务:
"dense": {
"api_base" : "<api-endpoint>", // API 服务端点地址
"api_key" : "<your-api-key>", // 模型服务的 API 密钥
- "provider" : "<provider-type>", // 提供商类型(volcengine 或 openai)
+ "provider" : "<provider-type>", // 提供商类型(volcengine、openai 或 jina)
"dimension": 1024, // 向量维度
"model" : "<model-name>" // Embedding 模型名称(如 doubao-embedding-vision-250615 或 text-embedding-3-large)
}
@@ -99,7 +99,7 @@ OpenViking 支持多种模型服务:
"vlm": {
"api_base" : "<api-endpoint>", // API 服务端点地址
"api_key" : "<your-api-key>", // 模型服务的 API 密钥
- "provider" : "<provider-type>", // 提供商类型(volcengine 或 openai)
+ "provider" : "<provider-type>", // 提供商类型(volcengine、openai 或 jina)
"model" : "<model-name>" // VLM 模型名称(如 doubao-seed-1-8-251228 或 gpt-4-vision-preview)
}
}
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index 7b1b9c330..97cd52c35 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -35,7 +35,7 @@ Minimal configuration example:
"dense": {
"api_base": "<api-endpoint>",
"api_key": "<your-api-key>",
- "provider": "<volcengine|openai>",
+ "provider": "<volcengine|openai|jina>",
"dimension": 1024,
"model": "<model-name>"
}
@@ -43,7 +43,7 @@ Minimal configuration example:
"vlm": {
"api_base": "<api-endpoint>",
"api_key": "<your-api-key>",
- "provider": "<volcengine|openai>",
+ "provider": "<volcengine|openai|jina>",
"model": "<model-name>"
}
}
diff --git a/docs/en/faq/faq.md b/docs/en/faq/faq.md
index 4cc8a9f9d..2f15f3f2e 100644
--- a/docs/en/faq/faq.md
+++ b/docs/en/faq/faq.md
@@ -109,6 +109,7 @@ Config files at the default path `~/.openviking/ov.conf` are loaded automaticall
| `volcengine` | Volcengine Embedding API (Recommended) |
| `openai` | OpenAI Embedding API |
| `vikingdb` | VikingDB Embedding API |
+| `jina` | Jina AI Embedding API |
Supports Dense, Sparse, and Hybrid embedding modes.
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 6442210e5..7c3c0fb2a 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -118,7 +118,7 @@ Embedding model configuration for vector search, supporting dense, sparse, and h
| Parameter | Type | Description |
|-----------|------|-------------|
-| `provider` | str | `"volcengine"`, `"openai"`, or `"vikingdb"` |
+| `provider` | str | `"volcengine"`, `"openai"`, `"vikingdb"`, or `"jina"` |
| `api_key` | str | API key |
| `model` | str | Model name |
| `dimension` | int | Vector dimension |
@@ -138,6 +138,7 @@ With `input: "multimodal"`, OpenViking can embed text, images (PNG, JPG, etc.),
- `openai`: OpenAI Embedding API
- `volcengine`: Volcengine Embedding API
- `vikingdb`: VikingDB Embedding API
+- `jina`: Jina AI Embedding API
**vikingdb provider example:**
@@ -156,6 +157,43 @@ With `input: "multimodal"`, OpenViking can embed text, images (PNG, JPG, etc.),
}
```
+**jina provider example:**
+
+```json
+{
+ "embedding": {
+ "dense": {
+ "provider": "jina",
+ "api_key": "jina_xxx",
+ "model": "jina-embeddings-v5-text-small",
+ "dimension": 1024
+ }
+ }
+}
+```
+
+Available Jina models:
+- `jina-embeddings-v5-text-small`: 677M params, 1024 dim, max seq 32768 (default)
+- `jina-embeddings-v5-text-nano`: 239M params, 768 dim, max seq 8192
+
+Get your API key at https://jina.ai
+
+**Local deployment (GGUF/MLX):** Jina embedding models are open-weight and available in GGUF and MLX formats on [Hugging Face](https://huggingface.co/jinaai). You can run them locally with any OpenAI-compatible server (e.g. llama.cpp, MLX, vLLM) and point the `api_base` to your local endpoint:
+
+```json
+{
+ "embedding": {
+ "dense": {
+ "provider": "jina",
+ "api_key": "local",
+ "api_base": "http://localhost:8080/v1",
+ "model": "jina-embeddings-v5-text-nano",
+ "dimension": 768
+ }
+ }
+}
+```
+
#### Sparse Embedding
```json
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 1cbdbcf95..28dbf6a7e 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -35,7 +35,7 @@ export OPENVIKING_CONFIG_FILE=/path/to/ov.conf
"dense": {
"api_base": "<api-endpoint>",
"api_key": "<your-api-key>",
- "provider": "<volcengine|openai>",
+ "provider": "<volcengine|openai|jina>",
"dimension": 1024,
"model": "<model-name>"
}
@@ -43,7 +43,7 @@ export OPENVIKING_CONFIG_FILE=/path/to/ov.conf
"vlm": {
"api_base": "<api-endpoint>",
"api_key": "<your-api-key>",
- "provider": "<volcengine|openai>",
+ "provider": "<volcengine|openai|jina>",
"model": "<model-name>"
}
}
diff --git a/docs/zh/faq/faq.md b/docs/zh/faq/faq.md
index d3f7ba3b7..05d240e25 100644
--- a/docs/zh/faq/faq.md
+++ b/docs/zh/faq/faq.md
@@ -109,6 +109,7 @@ pip install openviking
| `volcengine` | 火山引擎 Embedding API(推荐) |
| `openai` | OpenAI Embedding API |
| `vikingdb` | VikingDB Embedding API |
+| `jina` | Jina AI Embedding API |
支持 Dense、Sparse 和 Hybrid 三种 Embedding 模式。
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 7ee667626..ec70d4bd4 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -120,7 +120,7 @@ OpenViking 使用 JSON 配置文件(`ov.conf`)进行设置。配置文件支
| 参数 | 类型 | 说明 |
|------|------|------|
-| `provider` | str | `"volcengine"`、`"openai"` 或 `"vikingdb"` |
+| `provider` | str | `"volcengine"`、`"openai"`、`"vikingdb"` 或 `"jina"` |
| `api_key` | str | API Key |
| `model` | str | 模型名称 |
| `dimension` | int | 向量维度 |
@@ -140,6 +140,7 @@ OpenViking 使用 JSON 配置文件(`ov.conf`)进行设置。配置文件支
- `openai`: OpenAI Embedding API
- `volcengine`: 火山引擎 Embedding API
- `vikingdb`: VikingDB Embedding API
+- `jina`: Jina AI Embedding API
**vikingdb provider 配置示例:**
@@ -158,6 +159,43 @@ OpenViking 使用 JSON 配置文件(`ov.conf`)进行设置。配置文件支
}
```
+**jina provider 配置示例:**
+
+```json
+{
+ "embedding": {
+ "dense": {
+ "provider": "jina",
+ "api_key": "jina_xxx",
+ "model": "jina-embeddings-v5-text-small",
+ "dimension": 1024
+ }
+ }
+}
+```
+
+可用 Jina 模型:
+- `jina-embeddings-v5-text-small`: 677M 参数, 1024 维, 最大序列长度 32768 (默认)
+- `jina-embeddings-v5-text-nano`: 239M 参数, 768 维, 最大序列长度 8192
+
+**本地部署 (GGUF/MLX):** Jina 嵌入模型是开源的, 在 [Hugging Face](https://huggingface.co/jinaai) 上提供 GGUF 和 MLX 格式。可以使用任何 OpenAI 兼容的推理服务器 (如 llama.cpp、MLX、vLLM) 本地运行, 并将 `api_base` 指向本地端点:
+
+```json
+{
+ "embedding": {
+ "dense": {
+ "provider": "jina",
+ "api_key": "local",
+ "api_base": "http://localhost:8080/v1",
+ "model": "jina-embeddings-v5-text-nano",
+ "dimension": 768
+ }
+ }
+}
+```
+
+获取 API Key: https://jina.ai
+
#### Sparse Embedding
```json
diff --git a/openviking/models/embedder/__init__.py b/openviking/models/embedder/__init__.py
index 30f459590..9ce209caa 100644
--- a/openviking/models/embedder/__init__.py
+++ b/openviking/models/embedder/__init__.py
@@ -11,6 +11,7 @@ Provides three embedder abstractions:
Supported providers:
- OpenAI: Dense only
- Volcengine: Dense, Sparse, Hybrid
+- Jina AI: Dense only
"""
from openviking.models.embedder.base import (
@@ -21,6 +22,7 @@ from openviking.models.embedder.base import (
HybridEmbedderBase,
SparseEmbedderBase,
)
+from openviking.models.embedder.jina_embedders import JinaDenseEmbedder
from openviking.models.embedder.openai_embedders import OpenAIDenseEmbedder
from openviking.models.embedder.vikingdb_embedders import (
VikingDBDenseEmbedder,
@@ -41,6 +43,8 @@ __all__ = [
"SparseEmbedderBase",
"HybridEmbedderBase",
"CompositeHybridEmbedder",
+ # Jina AI implementations
+ "JinaDenseEmbedder",
# OpenAI implementations
"OpenAIDenseEmbedder",
# Volcengine implementations
diff --git a/openviking/models/embedder/jina_embedders.py b/openviking/models/embedder/jina_embedders.py
new file mode 100644
index 000000000..d0c9b3964
--- /dev/null
+++ b/openviking/models/embedder/jina_embedders.py
@@ -0,0 +1,169 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Jina AI Embedder Implementation"""
+
+from typing import Any, Dict, List, Optional
+
+import openai
+
+from openviking.models.embedder.base import (
+ DenseEmbedderBase,
+ EmbedResult,
+)
+
+# Default dimensions for Jina embedding models
+JINA_MODEL_DIMENSIONS = {
+ "jina-embeddings-v5-text-small": 1024, # 677M params, max seq 32768
+ "jina-embeddings-v5-text-nano": 768, # 239M params, max seq 8192
+}
+
+
+class JinaDenseEmbedder(DenseEmbedderBase):
+ """Jina AI Dense Embedder Implementation
+
+ Uses Jina AI embedding API via OpenAI-compatible client.
+ Supports task-specific embeddings and Matryoshka dimension reduction.
+
+ Example:
+ >>> embedder = JinaDenseEmbedder(
+ ... model_name="jina-embeddings-v5-text-small",
+ ... api_key="jina_xxx",
+ ... dimension=512,
+ ... task="retrieval.query"
+ ... )
+ >>> result = embedder.embed("Hello world")
+ >>> print(len(result.dense_vector))
+ 512
+ """
+
+ def __init__(
+ self,
+ model_name: str = "jina-embeddings-v5-text-small",
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ dimension: Optional[int] = None,
+ task: Optional[str] = None,
+ late_chunking: Optional[bool] = None,
+ config: Optional[Dict[str, Any]] = None,
+ ):
+ """Initialize Jina AI Dense Embedder
+
+ Args:
+ model_name: Jina model name, defaults to jina-embeddings-v5-text-small
+ api_key: API key, required
+ api_base: API base URL, defaults to https://api.jina.ai/v1
+ dimension: Dimension for Matryoshka reduction, optional
+ task: Task type for task-specific embeddings, optional.
+ Valid values: retrieval.query, retrieval.passage,
+ text-matching, classification, separation
+ late_chunking: Enable late chunking via extra_body, optional
+ config: Additional configuration dict
+
+ Raises:
+ ValueError: If api_key is not provided
+ """
+ super().__init__(model_name, config)
+
+ self.api_key = api_key
+ self.api_base = api_base or "https://api.jina.ai/v1"
+ self.dimension = dimension
+ self.task = task
+ self.late_chunking = late_chunking
+
+ if not self.api_key:
+ raise ValueError("api_key is required")
+
+ # Initialize OpenAI-compatible client with Jina base URL
+ self.client = openai.OpenAI(
+ api_key=self.api_key,
+ base_url=self.api_base,
+ )
+
+ # Determine dimension
+ max_dim = JINA_MODEL_DIMENSIONS.get(model_name, 1024)
+ if dimension is not None and dimension > max_dim:
+ raise ValueError(
+ f"Requested dimension {dimension} exceeds maximum {max_dim} for model '{model_name}'. "
+ f"Jina models support Matryoshka dimension reduction up to {max_dim}."
+ )
+ self._dimension = dimension if dimension is not None else max_dim
+
+ def _build_extra_body(self) -> Optional[Dict[str, Any]]:
+ """Build extra_body dict for Jina-specific parameters"""
+ extra_body = {}
+ if self.task is not None:
+ extra_body["task"] = self.task
+ if self.late_chunking is not None:
+ extra_body["late_chunking"] = self.late_chunking
+ return extra_body if extra_body else None
+
+ def embed(self, text: str) -> EmbedResult:
+ """Perform dense embedding on text
+
+ Args:
+ text: Input text
+
+ Returns:
+ EmbedResult: Result containing only dense_vector
+
+ Raises:
+ RuntimeError: When API call fails
+ """
+ try:
+ kwargs: Dict[str, Any] = {"input": text, "model": self.model_name}
+ if self.dimension:
+ kwargs["dimensions"] = self.dimension
+
+ extra_body = self._build_extra_body()
+ if extra_body:
+ kwargs["extra_body"] = extra_body
+
+ response = self.client.embeddings.create(**kwargs)
+ vector = response.data[0].embedding
+
+ return EmbedResult(dense_vector=vector)
+ except openai.APIError as e:
+ raise RuntimeError(f"Jina API error: {e.message}") from e
+ except Exception as e:
+ raise RuntimeError(f"Embedding failed: {str(e)}") from e
+
+ def embed_batch(self, texts: List[str]) -> List[EmbedResult]:
+ """Batch embedding (Jina native support)
+
+ Args:
+ texts: List of texts
+
+ Returns:
+ List[EmbedResult]: List of embedding results
+
+ Raises:
+ RuntimeError: When API call fails
+ """
+ if not texts:
+ return []
+
+ try:
+ kwargs: Dict[str, Any] = {"input": texts, "model": self.model_name}
+ if self.dimension:
+ kwargs["dimensions"] = self.dimension
+
+ extra_body = self._build_extra_body()
+ if extra_body:
+ kwargs["extra_body"] = extra_body
+
+ response = self.client.embeddings.create(**kwargs)
+
+ return [EmbedResult(dense_vector=item.embedding) for item in response.data]
+ except openai.APIError as e:
+ raise RuntimeError(f"Jina API error: {e.message}") from e
+ except Exception as e:
+ raise RuntimeError(f"Batch embedding failed: {str(e)}") from e
+
+ def get_dimension(self) -> int:
+ """Get embedding dimension
+
+ Returns:
+ int: Vector dimension
+ """
+ return self._dimension
+
diff --git a/openviking_cli/utils/config/embedding_config.py b/openviking_cli/utils/config/embedding_config.py
index e86e9ed31..ba9aab96e 100644
--- a/openviking_cli/utils/config/embedding_config.py
+++ b/openviking_cli/utils/config/embedding_config.py
@@ -15,7 +15,7 @@ class EmbeddingModelConfig(BaseModel):
batch_size: int = Field(default=32, description="Batch size for embedding generation")
input: str = Field(default="multimodal", description="Input type: 'text' or 'multimodal'")
provider: Optional[str] = Field(
- default="volcengine", description="Provider type: 'openai', 'volcengine', 'vikingdb'"
+ default="volcengine", description="Provider type: 'openai', 'volcengine', 'vikingdb', 'jina'"
)
backend: Optional[str] = Field(
default="volcengine",
@@ -52,9 +52,9 @@ class EmbeddingModelConfig(BaseModel):
if not self.provider:
raise ValueError("Embedding provider is required")
- if self.provider not in ["openai", "volcengine", "vikingdb"]:
+ if self.provider not in ["openai", "volcengine", "vikingdb", "jina"]:
raise ValueError(
- f"Invalid embedding provider: '{self.provider}'. Must be one of: 'openai', 'volcengine', 'vikingdb'"
+ f"Invalid embedding provider: '{self.provider}'. Must be one of: 'openai', 'volcengine', 'vikingdb', 'jina'"
)
# Provider-specific validation
@@ -80,6 +80,10 @@ class EmbeddingModelConfig(BaseModel):
f"VikingDB provider requires the following fields: {', '.join(missing)}"
)
+ elif self.provider == "jina":
+ if not self.api_key:
+ raise ValueError("Jina provider requires 'api_key' to be set")
+
return self
@@ -125,6 +129,7 @@ class EmbeddingConfig(BaseModel):
ValueError: If provider/type combination is not supported
"""
from openviking.models.embedder import (
+ JinaDenseEmbedder,
OpenAIDenseEmbedder,
VikingDBDenseEmbedder,
VikingDBHybridEmbedder,
@@ -210,6 +215,15 @@ class EmbeddingConfig(BaseModel):
"input_type": cfg.input,
},
),
+ ("jina", "dense"): (
+ JinaDenseEmbedder,
+ lambda cfg: {
+ "model_name": cfg.model,
+ "api_key": cfg.api_key,
+ "api_base": cfg.api_base,
+ "dimension": cfg.dimension,
+ },
+ ),
}
key = (provider, embedder_type)
diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py
new file mode 100644
index 000000000..819b3465d
--- /dev/null
+++ b/tests/unit/__init__.py
@@ -0,0 +1,2 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
diff --git a/tests/unit/test_jina_embedder.py b/tests/unit/test_jina_embedder.py
new file mode 100644
index 000000000..67a926681
--- /dev/null
+++ b/tests/unit/test_jina_embedder.py
@@ -0,0 +1,271 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for Jina AI Embedder"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openviking.models.embedder import JinaDenseEmbedder
+from openviking.models.embedder.jina_embedders import (
+ JINA_MODEL_DIMENSIONS,
+)
+
+
+class TestJinaDenseEmbedder:
+ """Test cases for JinaDenseEmbedder"""
+
+ def test_init_requires_api_key(self):
+ """Test that api_key is required"""
+ with pytest.raises(ValueError, match="api_key is required"):
+ JinaDenseEmbedder(model_name="jina-embeddings-v5-text-small")
+
+ def test_init_with_api_key(self):
+ """Test initialization with api_key"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ )
+ assert embedder.api_key == "test-api-key"
+ assert embedder.model_name == "jina-embeddings-v5-text-small"
+ assert embedder.api_base == "https://api.jina.ai/v1"
+
+ def test_init_with_custom_api_base(self):
+ """Test initialization with custom api_base"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ api_base="https://custom.api.jina.ai/v1",
+ )
+ assert embedder.api_base == "https://custom.api.jina.ai/v1"
+
+ def test_default_dimension_v5_small(self):
+ """Test default dimension for jina-embeddings-v5-text-small"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ )
+ assert embedder.get_dimension() == 1024
+
+ def test_default_dimension_v5_nano(self):
+ """Test default dimension for jina-embeddings-v5-text-nano"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-nano",
+ api_key="test-api-key",
+ )
+ assert embedder.get_dimension() == 768
+
+ def test_custom_dimension(self):
+ """Test custom dimension for Matryoshka reduction"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ dimension=256,
+ )
+ assert embedder.get_dimension() == 256
+
+ def test_model_dimensions_constant(self):
+ """Test JINA_MODEL_DIMENSIONS constant"""
+ assert "jina-embeddings-v5-text-small" in JINA_MODEL_DIMENSIONS
+ assert "jina-embeddings-v5-text-nano" in JINA_MODEL_DIMENSIONS
+ assert JINA_MODEL_DIMENSIONS["jina-embeddings-v5-text-small"] == 1024
+ assert JINA_MODEL_DIMENSIONS["jina-embeddings-v5-text-nano"] == 768
+
+ @patch("openviking.models.embedder.jina_embedders.openai.OpenAI")
+ def test_embed_single_text(self, mock_openai_class):
+ """Test embedding a single text"""
+ # Setup mock
+ mock_client = MagicMock()
+ mock_openai_class.return_value = mock_client
+
+ mock_embedding = MagicMock()
+ mock_embedding.embedding = [0.1] * 1024
+
+ mock_response = MagicMock()
+ mock_response.data = [mock_embedding]
+ mock_client.embeddings.create.return_value = mock_response
+
+ # Create embedder and embed
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ )
+ result = embedder.embed("Hello world")
+
+ # Verify
+ assert result.dense_vector is not None
+ assert len(result.dense_vector) == 1024
+ mock_client.embeddings.create.assert_called_once()
+
+ @patch("openviking.models.embedder.jina_embedders.openai.OpenAI")
+ def test_embed_with_dimension(self, mock_openai_class):
+ """Test embedding with custom dimension parameter"""
+ mock_client = MagicMock()
+ mock_openai_class.return_value = mock_client
+
+ mock_embedding = MagicMock()
+ mock_embedding.embedding = [0.1] * 768
+
+ mock_response = MagicMock()
+ mock_response.data = [mock_embedding]
+ mock_client.embeddings.create.return_value = mock_response
+
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ dimension=768,
+ )
+ embedder.embed("Hello world")
+
+ # Check dimensions was passed
+ call_kwargs = mock_client.embeddings.create.call_args[1]
+ assert call_kwargs["dimensions"] == 768
+
+ @patch("openviking.models.embedder.jina_embedders.openai.OpenAI")
+ def test_embed_with_task(self, mock_openai_class):
+ """Test embedding with task parameter"""
+ mock_client = MagicMock()
+ mock_openai_class.return_value = mock_client
+
+ mock_embedding = MagicMock()
+ mock_embedding.embedding = [0.1] * 1024
+
+ mock_response = MagicMock()
+ mock_response.data = [mock_embedding]
+ mock_client.embeddings.create.return_value = mock_response
+
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ task="retrieval.query",
+ )
+ embedder.embed("Hello world")
+
+ # Check extra_body was passed with task
+ call_kwargs = mock_client.embeddings.create.call_args[1]
+ assert "extra_body" in call_kwargs
+ assert call_kwargs["extra_body"]["task"] == "retrieval.query"
+
+ @patch("openviking.models.embedder.jina_embedders.openai.OpenAI")
+ def test_embed_with_late_chunking(self, mock_openai_class):
+ """Test embedding with late_chunking parameter"""
+ mock_client = MagicMock()
+ mock_openai_class.return_value = mock_client
+
+ mock_embedding = MagicMock()
+ mock_embedding.embedding = [0.1] * 1024
+
+ mock_response = MagicMock()
+ mock_response.data = [mock_embedding]
+ mock_client.embeddings.create.return_value = mock_response
+
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ late_chunking=True,
+ )
+ embedder.embed("Hello world")
+
+ # Check extra_body was passed with late_chunking
+ call_kwargs = mock_client.embeddings.create.call_args[1]
+ assert "extra_body" in call_kwargs
+ assert call_kwargs["extra_body"]["late_chunking"] is True
+
+ @patch("openviking.models.embedder.jina_embedders.openai.OpenAI")
+ def test_embed_batch(self, mock_openai_class):
+ """Test batch embedding"""
+ mock_client = MagicMock()
+ mock_openai_class.return_value = mock_client
+
+ mock_embeddings = [MagicMock(embedding=[0.1] * 1024) for _ in range(3)]
+
+ mock_response = MagicMock()
+ mock_response.data = mock_embeddings
+ mock_client.embeddings.create.return_value = mock_response
+
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ )
+ results = embedder.embed_batch(["Hello", "World", "Test"])
+
+ assert len(results) == 3
+ for result in results:
+ assert result.dense_vector is not None
+ assert len(result.dense_vector) == 1024
+
+ @patch("openviking.models.embedder.jina_embedders.openai.OpenAI")
+ def test_embed_batch_empty(self, mock_openai_class):
+ """Test batch embedding with empty list"""
+ mock_client = MagicMock()
+ mock_openai_class.return_value = mock_client
+
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ )
+ results = embedder.embed_batch([])
+
+ assert results == []
+ mock_client.embeddings.create.assert_not_called()
+
+ @patch("openviking.models.embedder.jina_embedders.openai.OpenAI")
+ def test_embed_api_error(self, mock_openai_class):
+ """Test embedding with API error"""
+ import openai
+
+ mock_client = MagicMock()
+ mock_openai_class.return_value = mock_client
+
+ mock_client.embeddings.create.side_effect = openai.APIError(
+ message="Test API error",
+ request=MagicMock(),
+ body=None,
+ )
+
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ )
+
+ with pytest.raises(RuntimeError, match="Jina API error"):
+ embedder.embed("Hello world")
+
+ def test_build_extra_body_none(self):
+ """Test _build_extra_body returns None when no params set"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ )
+ assert embedder._build_extra_body() is None
+
+ def test_build_extra_body_with_params(self):
+ """Test _build_extra_body returns dict with params"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-small",
+ api_key="test-api-key",
+ task="retrieval.passage",
+ late_chunking=True,
+ )
+ extra_body = embedder._build_extra_body()
+ assert extra_body is not None
+ assert extra_body["task"] == "retrieval.passage"
+ assert extra_body["late_chunking"] is True
+
+ def test_dimension_validation_exceeds_max(self):
+ """Test that requesting dimension exceeding model max raises ValueError"""
+ with pytest.raises(ValueError, match="exceeds maximum"):
+ JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-nano",
+ api_key="test-key",
+ dimension=1024, # nano max is 768
+ )
+
+ def test_dimension_validation_within_range(self):
+ """Test that requesting dimension within model max works"""
+ embedder = JinaDenseEmbedder(
+ model_name="jina-embeddings-v5-text-nano",
+ api_key="test-key",
+ dimension=256,
+ )
+ assert embedder.get_dimension() == 256