|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +import asyncio |
| 17 | +from typing import List, Optional |
| 18 | + |
| 19 | +from .base import EmbeddingModel |
| 20 | + |
| 21 | + |
| 22 | +class GoogleEmbeddingModel(EmbeddingModel): |
| 23 | + """Embedding model using Gemini API. |
| 24 | +
|
| 25 | + This class is a wrapper for using embedding models powered by Gemini API. |
| 26 | +
|
| 27 | + To use, you must have either: |
| 28 | +
|
| 29 | + 1. The ``GOOGLE_API_KEY`` environment variable set with your API key, or |
| 30 | + 2. Pass your API key using the api_key kwarg to the genai.Client(). |
| 31 | +
|
| 32 | + Args: |
| 33 | + embedding_model (str): The name of the embedding model to be used. |
| 34 | + **kwargs: Additional keyword arguments. Supports: |
| 35 | + - output_dimensionality (int, optional): Desired output dimensions (128-3072 for gemini-embedding-001). |
| 36 | + Recommended values: 768, 1536, or 3072. If not specified, API defaults to 3072. |
| 37 | + - api_key (str, optional): API key for authentication (or use GOOGLE_API_KEY env var). |
| 38 | + - Other arguments passed to genai.Client() constructor. |
| 39 | +
|
| 40 | + Attributes: |
| 41 | + model (str): The name of the embedding model. |
| 42 | + embedding_size (int): The size of the embeddings. |
| 43 | + """ |
| 44 | + |
| 45 | + engine_name = "google" |
| 46 | + |
| 47 | + def __init__(self, embedding_model: str, **kwargs): |
| 48 | + try: |
| 49 | + from google import genai |
| 50 | + |
| 51 | + except ImportError: |
| 52 | + raise ImportError( |
| 53 | + "Could not import google-genai, please install it with " |
| 54 | + "`pip install google-genai`." |
| 55 | + ) |
| 56 | + |
| 57 | + self.model = embedding_model |
| 58 | + self.output_dimensionality = kwargs.pop("output_dimensionality", None) |
| 59 | + |
| 60 | + self.client = genai.Client(**kwargs) |
| 61 | + |
| 62 | + embedding_size_dict = { |
| 63 | + "gemini-embedding-001": 3072, |
| 64 | + } |
| 65 | + |
| 66 | + if self.model in embedding_size_dict: |
| 67 | + self._embedding_size = ( |
| 68 | + self.output_dimensionality |
| 69 | + if self.output_dimensionality is not None |
| 70 | + else embedding_size_dict[self.model] |
| 71 | + ) |
| 72 | + else: |
| 73 | + self._embedding_size = None |
| 74 | + |
| 75 | + @property |
| 76 | + def embedding_size(self) -> int: |
| 77 | + if self._embedding_size is None: |
| 78 | + self._embedding_size = len(self.encode(["test"])[0]) |
| 79 | + return self._embedding_size |
| 80 | + |
| 81 | + async def encode_async(self, documents: List[str]) -> List[List[float]]: |
| 82 | + """Encode a list of documents into their corresponding sentence embeddings. |
| 83 | +
|
| 84 | + Args: |
| 85 | + documents (List[str]): The list of documents to be encoded. |
| 86 | +
|
| 87 | + Returns: |
| 88 | + List[List[float]]: The list of sentence embeddings, where each embedding is a list of floats. |
| 89 | + """ |
| 90 | + loop = asyncio.get_running_loop() |
| 91 | + embeddings = await loop.run_in_executor(None, self.encode, documents) |
| 92 | + |
| 93 | + return embeddings |
| 94 | + |
| 95 | + def encode(self, documents: List[str]) -> List[List[float]]: |
| 96 | + """Encode a list of documents into their corresponding sentence embeddings. |
| 97 | +
|
| 98 | + Args: |
| 99 | + documents (List[str]): The list of documents to be encoded. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + List[List[float]]: The list of sentence embeddings, where each embedding is a list of floats. |
| 103 | +
|
| 104 | + Raises: |
| 105 | + RuntimeError: If the embedding request fails. |
| 106 | + """ |
| 107 | + try: |
| 108 | + embed_kwargs = {"model": self.model, "contents": documents} |
| 109 | + if self.output_dimensionality is not None: |
| 110 | + embed_kwargs["output_dimensionality"] = self.output_dimensionality |
| 111 | + |
| 112 | + results = self.client.models.embed_content(**embed_kwargs) |
| 113 | + return [emb.values for emb in results.embeddings] |
| 114 | + except Exception as e: |
| 115 | + raise RuntimeError(f"Failed to retrieve embeddings: {e}") from e |
0 commit comments