|
| 1 | +# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +"""Jina AI Embedder Implementation""" |
| 4 | + |
| 5 | +from typing import Any, Dict, List, Optional |
| 6 | + |
| 7 | +import openai |
| 8 | + |
| 9 | +from openviking.models.embedder.base import ( |
| 10 | + DenseEmbedderBase, |
| 11 | + EmbedResult, |
| 12 | +) |
| 13 | + |
| 14 | +# Default dimensions for Jina embedding models |
| 15 | +JINA_MODEL_DIMENSIONS = { |
| 16 | + "jina-embeddings-v5-text-small": 1024, # 677M params, max seq 32768 |
| 17 | + "jina-embeddings-v5-text-nano": 768, # 239M params, max seq 8192 |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +class JinaDenseEmbedder(DenseEmbedderBase): |
| 22 | + """Jina AI Dense Embedder Implementation |
| 23 | +
|
| 24 | + Uses Jina AI embedding API via OpenAI-compatible client. |
| 25 | + Supports task-specific embeddings and Matryoshka dimension reduction. |
| 26 | +
|
| 27 | + Example: |
| 28 | + >>> embedder = JinaDenseEmbedder( |
| 29 | + ... model_name="jina-embeddings-v5-text-small", |
| 30 | + ... api_key="jina_xxx", |
| 31 | + ... dimension=512, |
| 32 | + ... task="retrieval.query" |
| 33 | + ... ) |
| 34 | + >>> result = embedder.embed("Hello world") |
| 35 | + >>> print(len(result.dense_vector)) |
| 36 | + 512 |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + model_name: str = "jina-embeddings-v5-text-small", |
| 42 | + api_key: Optional[str] = None, |
| 43 | + api_base: Optional[str] = None, |
| 44 | + dimension: Optional[int] = None, |
| 45 | + task: Optional[str] = None, |
| 46 | + late_chunking: Optional[bool] = None, |
| 47 | + config: Optional[Dict[str, Any]] = None, |
| 48 | + ): |
| 49 | + """Initialize Jina AI Dense Embedder |
| 50 | +
|
| 51 | + Args: |
| 52 | + model_name: Jina model name, defaults to jina-embeddings-v5-text-small |
| 53 | + api_key: API key, required |
| 54 | + api_base: API base URL, defaults to https://api.jina.ai/v1 |
| 55 | + dimension: Dimension for Matryoshka reduction, optional |
| 56 | + task: Task type for task-specific embeddings, optional. |
| 57 | + Valid values: retrieval.query, retrieval.passage, |
| 58 | + text-matching, classification, separation |
| 59 | + late_chunking: Enable late chunking via extra_body, optional |
| 60 | + config: Additional configuration dict |
| 61 | +
|
| 62 | + Raises: |
| 63 | + ValueError: If api_key is not provided |
| 64 | + """ |
| 65 | + super().__init__(model_name, config) |
| 66 | + |
| 67 | + self.api_key = api_key |
| 68 | + self.api_base = api_base or "https://api.jina.ai/v1" |
| 69 | + self.dimension = dimension |
| 70 | + self.task = task |
| 71 | + self.late_chunking = late_chunking |
| 72 | + |
| 73 | + if not self.api_key: |
| 74 | + raise ValueError("api_key is required") |
| 75 | + |
| 76 | + # Initialize OpenAI-compatible client with Jina base URL |
| 77 | + self.client = openai.OpenAI( |
| 78 | + api_key=self.api_key, |
| 79 | + base_url=self.api_base, |
| 80 | + ) |
| 81 | + |
| 82 | + # Determine dimension |
| 83 | + max_dim = JINA_MODEL_DIMENSIONS.get(model_name, 1024) |
| 84 | + if dimension is not None and dimension > max_dim: |
| 85 | + raise ValueError( |
| 86 | + f"Requested dimension {dimension} exceeds maximum {max_dim} for model '{model_name}'. " |
| 87 | + f"Jina models support Matryoshka dimension reduction up to {max_dim}." |
| 88 | + ) |
| 89 | + self._dimension = dimension if dimension is not None else max_dim |
| 90 | + |
| 91 | + def _build_extra_body(self) -> Optional[Dict[str, Any]]: |
| 92 | + """Build extra_body dict for Jina-specific parameters""" |
| 93 | + extra_body = {} |
| 94 | + if self.task is not None: |
| 95 | + extra_body["task"] = self.task |
| 96 | + if self.late_chunking is not None: |
| 97 | + extra_body["late_chunking"] = self.late_chunking |
| 98 | + return extra_body if extra_body else None |
| 99 | + |
| 100 | + def embed(self, text: str) -> EmbedResult: |
| 101 | + """Perform dense embedding on text |
| 102 | +
|
| 103 | + Args: |
| 104 | + text: Input text |
| 105 | +
|
| 106 | + Returns: |
| 107 | + EmbedResult: Result containing only dense_vector |
| 108 | +
|
| 109 | + Raises: |
| 110 | + RuntimeError: When API call fails |
| 111 | + """ |
| 112 | + try: |
| 113 | + kwargs: Dict[str, Any] = {"input": text, "model": self.model_name} |
| 114 | + if self.dimension: |
| 115 | + kwargs["dimensions"] = self.dimension |
| 116 | + |
| 117 | + extra_body = self._build_extra_body() |
| 118 | + if extra_body: |
| 119 | + kwargs["extra_body"] = extra_body |
| 120 | + |
| 121 | + response = self.client.embeddings.create(**kwargs) |
| 122 | + vector = response.data[0].embedding |
| 123 | + |
| 124 | + return EmbedResult(dense_vector=vector) |
| 125 | + except openai.APIError as e: |
| 126 | + raise RuntimeError(f"Jina API error: {e.message}") from e |
| 127 | + except Exception as e: |
| 128 | + raise RuntimeError(f"Embedding failed: {str(e)}") from e |
| 129 | + |
| 130 | + def embed_batch(self, texts: List[str]) -> List[EmbedResult]: |
| 131 | + """Batch embedding (Jina native support) |
| 132 | +
|
| 133 | + Args: |
| 134 | + texts: List of texts |
| 135 | +
|
| 136 | + Returns: |
| 137 | + List[EmbedResult]: List of embedding results |
| 138 | +
|
| 139 | + Raises: |
| 140 | + RuntimeError: When API call fails |
| 141 | + """ |
| 142 | + if not texts: |
| 143 | + return [] |
| 144 | + |
| 145 | + try: |
| 146 | + kwargs: Dict[str, Any] = {"input": texts, "model": self.model_name} |
| 147 | + if self.dimension: |
| 148 | + kwargs["dimensions"] = self.dimension |
| 149 | + |
| 150 | + extra_body = self._build_extra_body() |
| 151 | + if extra_body: |
| 152 | + kwargs["extra_body"] = extra_body |
| 153 | + |
| 154 | + response = self.client.embeddings.create(**kwargs) |
| 155 | + |
| 156 | + return [EmbedResult(dense_vector=item.embedding) for item in response.data] |
| 157 | + except openai.APIError as e: |
| 158 | + raise RuntimeError(f"Jina API error: {e.message}") from e |
| 159 | + except Exception as e: |
| 160 | + raise RuntimeError(f"Batch embedding failed: {str(e)}") from e |
| 161 | + |
| 162 | + def get_dimension(self) -> int: |
| 163 | + """Get embedding dimension |
| 164 | +
|
| 165 | + Returns: |
| 166 | + int: Vector dimension |
| 167 | + """ |
| 168 | + return self._dimension |
| 169 | + |
0 commit comments