|
| 1 | +# Copyright 2025-present the zvec project |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +from functools import lru_cache |
| 17 | +from typing import Optional |
| 18 | + |
| 19 | +from ..common.constants import TEXT, DenseVectorType |
| 20 | +from .embedding_function import DenseEmbeddingFunction |
| 21 | +from .jina_function import JinaFunctionBase |
| 22 | + |
| 23 | + |
| 24 | +class JinaDenseEmbedding(JinaFunctionBase, DenseEmbeddingFunction[TEXT]): |
| 25 | + """Dense text embedding function using Jina AI API. |
| 26 | +
|
| 27 | + This class provides text-to-vector embedding capabilities using Jina AI's |
| 28 | + embedding models. It inherits from ``DenseEmbeddingFunction`` and implements |
| 29 | + dense text embedding via the Jina Embeddings API (OpenAI-compatible). |
| 30 | +
|
| 31 | + Jina Embeddings v5 models support task-specific embedding through the |
| 32 | + ``task`` parameter, which optimizes the embedding for different use cases |
| 33 | + such as retrieval, text matching, or classification. They also support |
| 34 | + Matryoshka Representation Learning, allowing flexible output dimensions. |
| 35 | +
|
| 36 | + Args: |
| 37 | + model (str, optional): Jina embedding model identifier. |
| 38 | + Defaults to ``"jina-embeddings-v5-text-nano"``. Available models: |
| 39 | + - ``"jina-embeddings-v5-text-nano"``: 768 dims, 239M params, 8K context |
| 40 | + - ``"jina-embeddings-v5-text-small"``: 1024 dims, 677M params, 32K context |
| 41 | + dimension (Optional[int], optional): Desired output embedding dimension. |
| 42 | + If ``None``, uses model's default dimension. Supports Matryoshka |
| 43 | + dimensions: 32, 64, 128, 256, 512, 768 (nano) / 1024 (small). |
| 44 | + Defaults to ``None``. |
| 45 | + api_key (Optional[str], optional): Jina API authentication key. |
| 46 | + If ``None``, reads from ``JINA_API_KEY`` environment variable. |
| 47 | + Obtain your key from: https://jina.ai/api-dashboard |
| 48 | + task (Optional[str], optional): Task type to optimize embeddings for. |
| 49 | + Defaults to ``None``. Valid values: |
| 50 | + - ``"retrieval.query"``: For search queries |
| 51 | + - ``"retrieval.passage"``: For documents/passages to be searched |
| 52 | + - ``"text-matching"``: For symmetric text similarity |
| 53 | + - ``"classification"``: For text classification |
| 54 | + - ``"separation"``: For clustering/separation tasks |
| 55 | +
|
| 56 | + Attributes: |
| 57 | + dimension (int): The embedding vector dimension. |
| 58 | + data_type (DataType): Always ``DataType.VECTOR_FP32`` for this implementation. |
| 59 | + model (str): The Jina model name being used. |
| 60 | + task (Optional[str]): The task type for embedding optimization. |
| 61 | +
|
| 62 | + Raises: |
| 63 | + ValueError: If API key is not provided and not found in environment, |
| 64 | + if task is not a valid task type, or if API returns an error response. |
| 65 | + TypeError: If input to ``embed()`` is not a string. |
| 66 | + RuntimeError: If network error or Jina service error occurs. |
| 67 | +
|
| 68 | + Note: |
| 69 | + - Requires Python 3.10, 3.11, or 3.12 |
| 70 | + - Requires the ``openai`` package: ``pip install openai`` |
| 71 | + - Jina API is OpenAI-compatible, so it uses the ``openai`` Python client |
| 72 | + - Embedding results are cached (LRU cache, maxsize=10) to reduce API calls |
| 73 | + - For retrieval tasks, use ``"retrieval.query"`` for queries and |
| 74 | + ``"retrieval.passage"`` for documents |
| 75 | + - API usage requires a Jina API key from https://jina.ai/api-dashboard |
| 76 | +
|
| 77 | + Examples: |
| 78 | + >>> # Basic usage with default model |
| 79 | + >>> from zvec.extension import JinaDenseEmbedding |
| 80 | + >>> import os |
| 81 | + >>> os.environ["JINA_API_KEY"] = "jina_..." |
| 82 | + >>> |
| 83 | + >>> emb_func = JinaDenseEmbedding() |
| 84 | + >>> vector = emb_func.embed("Hello, world!") |
| 85 | + >>> len(vector) |
| 86 | + 768 |
| 87 | +
|
| 88 | + >>> # Retrieval use case: embed queries and documents differently |
| 89 | + >>> query_emb = JinaDenseEmbedding(task="retrieval.query") |
| 90 | + >>> doc_emb = JinaDenseEmbedding(task="retrieval.passage") |
| 91 | + >>> |
| 92 | + >>> query_vector = query_emb.embed("What is machine learning?") |
| 93 | + >>> doc_vector = doc_emb.embed("Machine learning is a subset of AI...") |
| 94 | +
|
| 95 | + >>> # Using larger model with custom dimension (Matryoshka) |
| 96 | + >>> emb_func = JinaDenseEmbedding( |
| 97 | + ... model="jina-embeddings-v5-text-small", |
| 98 | + ... dimension=256, |
| 99 | + ... api_key="jina_...", |
| 100 | + ... task="text-matching", |
| 101 | + ... ) |
| 102 | + >>> vector = emb_func.embed("Semantic similarity comparison") |
| 103 | + >>> len(vector) |
| 104 | + 256 |
| 105 | +
|
| 106 | + >>> # Using with zvec collection |
| 107 | + >>> import zvec |
| 108 | + >>> emb_func = JinaDenseEmbedding(task="retrieval.passage") |
| 109 | + >>> schema = zvec.CollectionSchema( |
| 110 | + ... name="docs", |
| 111 | + ... vectors=zvec.VectorSchema( |
| 112 | + ... "embedding", zvec.DataType.VECTOR_FP32, emb_func.dimension |
| 113 | + ... ), |
| 114 | + ... ) |
| 115 | + >>> collection = zvec.create_and_open(path="./my_docs", schema=schema) |
| 116 | +
|
| 117 | + See Also: |
| 118 | + - ``DenseEmbeddingFunction``: Base class for dense embeddings |
| 119 | + - ``OpenAIDenseEmbedding``: Alternative using OpenAI API |
| 120 | + - ``QwenDenseEmbedding``: Alternative using Qwen/DashScope API |
| 121 | + - ``DefaultLocalDenseEmbedding``: Local model without API calls |
| 122 | + """ |
| 123 | + |
| 124 | + def __init__( |
| 125 | + self, |
| 126 | + model: str = "jina-embeddings-v5-text-nano", |
| 127 | + dimension: Optional[int] = None, |
| 128 | + api_key: Optional[str] = None, |
| 129 | + task: Optional[str] = None, |
| 130 | + **kwargs, |
| 131 | + ): |
| 132 | + """Initialize the Jina dense embedding function. |
| 133 | +
|
| 134 | + Args: |
| 135 | + model (str): Jina model name. Defaults to "jina-embeddings-v5-text-nano". |
| 136 | + dimension (Optional[int]): Target embedding dimension or None for default. |
| 137 | + api_key (Optional[str]): API key or None to use environment variable. |
| 138 | + task (Optional[str]): Task type for embedding optimization or None. |
| 139 | + **kwargs: Additional parameters for API calls. |
| 140 | +
|
| 141 | + Raises: |
| 142 | + ValueError: If API key is not provided and not in environment, |
| 143 | + or if task is not a valid task type. |
| 144 | + """ |
| 145 | + # Initialize base class for API connection |
| 146 | + JinaFunctionBase.__init__(self, model=model, api_key=api_key, task=task) |
| 147 | + |
| 148 | + # Store dimension configuration |
| 149 | + self._custom_dimension = dimension |
| 150 | + |
| 151 | + # Determine actual dimension |
| 152 | + if dimension is None: |
| 153 | + self._dimension = self._MODEL_DIMENSIONS.get(model, 768) |
| 154 | + else: |
| 155 | + self._dimension = dimension |
| 156 | + |
| 157 | + # Store extra attributes |
| 158 | + self._extra_params = kwargs |
| 159 | + |
| 160 | + @property |
| 161 | + def dimension(self) -> int: |
| 162 | + """int: The expected dimensionality of the embedding vector.""" |
| 163 | + return self._dimension |
| 164 | + |
| 165 | + @property |
| 166 | + def extra_params(self) -> dict: |
| 167 | + """dict: Extra parameters for model-specific customization.""" |
| 168 | + return self._extra_params |
| 169 | + |
| 170 | + def __call__(self, input: TEXT) -> DenseVectorType: |
| 171 | + """Make the embedding function callable.""" |
| 172 | + return self.embed(input) |
| 173 | + |
| 174 | + @lru_cache(maxsize=10) |
| 175 | + def embed(self, input: TEXT) -> DenseVectorType: |
| 176 | + """Generate dense embedding vector for the input text. |
| 177 | +
|
| 178 | + This method calls the Jina Embeddings API to convert input text |
| 179 | + into a dense vector representation. Results are cached to improve |
| 180 | + performance for repeated inputs. |
| 181 | +
|
| 182 | + Args: |
| 183 | + input (TEXT): Input text string to embed. Must be non-empty after |
| 184 | + stripping whitespace. Maximum length depends on model: |
| 185 | + 8192 tokens for v5-nano, 32768 tokens for v5-small. |
| 186 | +
|
| 187 | + Returns: |
| 188 | + DenseVectorType: A list of floats representing the embedding vector. |
| 189 | + Length equals ``self.dimension``. Example: |
| 190 | + ``[0.123, -0.456, 0.789, ...]`` |
| 191 | +
|
| 192 | + Raises: |
| 193 | + TypeError: If ``input`` is not a string. |
| 194 | + ValueError: If input is empty/whitespace-only, or if the API returns |
| 195 | + an error or malformed response. |
| 196 | + RuntimeError: If network connectivity issues or Jina service |
| 197 | + errors occur. |
| 198 | +
|
| 199 | + Examples: |
| 200 | + >>> emb = JinaDenseEmbedding(task="retrieval.query") |
| 201 | + >>> vector = emb.embed("What is deep learning?") |
| 202 | + >>> len(vector) |
| 203 | + 768 |
| 204 | + >>> isinstance(vector[0], float) |
| 205 | + True |
| 206 | +
|
| 207 | + >>> # Error: empty input |
| 208 | + >>> emb.embed(" ") |
| 209 | + ValueError: Input text cannot be empty or whitespace only |
| 210 | +
|
| 211 | + >>> # Error: non-string input |
| 212 | + >>> emb.embed(123) |
| 213 | + TypeError: Expected 'input' to be str, got int |
| 214 | +
|
| 215 | + Note: |
| 216 | + - This method is cached (maxsize=10). Identical inputs return cached results. |
| 217 | + - The cache is based on exact string match (case-sensitive). |
| 218 | + - Task type affects embedding optimization but not caching behavior. |
| 219 | + """ |
| 220 | + if not isinstance(input, TEXT): |
| 221 | + raise TypeError(f"Expected 'input' to be str, got {type(input).__name__}") |
| 222 | + |
| 223 | + input = input.strip() |
| 224 | + if not input: |
| 225 | + raise ValueError("Input text cannot be empty or whitespace only") |
| 226 | + |
| 227 | + # Call API |
| 228 | + embedding_vector = self._call_text_embedding_api( |
| 229 | + input=input, |
| 230 | + dimension=self._custom_dimension, |
| 231 | + ) |
| 232 | + |
| 233 | + # Verify dimension |
| 234 | + if len(embedding_vector) != self.dimension: |
| 235 | + raise ValueError( |
| 236 | + f"Dimension mismatch: expected {self.dimension}, " |
| 237 | + f"got {len(embedding_vector)}" |
| 238 | + ) |
| 239 | + |
| 240 | + return embedding_vector |
0 commit comments