|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023 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 | +import os |
| 18 | +from typing import List |
| 19 | + |
| 20 | +from .base import EmbeddingModel |
| 21 | + |
| 22 | + |
| 23 | +def get_executor(): |
| 24 | + from . import embeddings_executor |
| 25 | + |
| 26 | + return embeddings_executor |
| 27 | + |
| 28 | + |
| 29 | +class AzureEmbeddingModel(EmbeddingModel): |
| 30 | + """Embedding model using Azure OpenAI. |
| 31 | +
|
| 32 | + This class represents an embedding model that utilizes the Azure OpenAI API |
| 33 | + for generating text embeddings. |
| 34 | +
|
| 35 | + Args: |
| 36 | + embedding_model (str): The name of the Azure OpenAI deployment model (e.g., "text-embedding-ada-002"). |
| 37 | + """ |
| 38 | + |
| 39 | + engine_name = "AzureOpenAI" |
| 40 | + |
| 41 | + # Lookup table for model embedding dimensions |
| 42 | + MODEL_DIMENSIONS = { |
| 43 | + "text-embedding-ada-002": 1536, |
| 44 | + # Add more models and their dimensions here if needed |
| 45 | + } |
| 46 | + |
| 47 | + def __init__(self, embedding_model: str): |
| 48 | + try: |
| 49 | + from openai import AzureOpenAI |
| 50 | + except ImportError: |
| 51 | + raise ImportError( |
| 52 | + "Could not import openai, please install it with " |
| 53 | + "`pip install openai`." |
| 54 | + ) |
| 55 | + # Set Azure OpenAI API credentials |
| 56 | + self.client = AzureOpenAI( |
| 57 | + api_key=os.getenv("AZURE_OPENAI_API_KEY"), |
| 58 | + api_version=os.getenv("AZURE_OPENAI_API_VERSION"), |
| 59 | + azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), |
| 60 | + ) |
| 61 | + |
| 62 | + self.embedding_model = embedding_model |
| 63 | + self.embedding_size = self._get_embedding_dimension() |
| 64 | + |
| 65 | + def _get_embedding_dimension(self): |
| 66 | + """Retrieve the embedding dimension for the specified model.""" |
| 67 | + if self.embedding_model in self.MODEL_DIMENSIONS: |
| 68 | + return self.MODEL_DIMENSIONS[self.embedding_model] |
| 69 | + else: |
| 70 | + embedding_size = len(self.encode(["test"])[0]) |
| 71 | + return embedding_size |
| 72 | + |
| 73 | + async def encode_async(self, documents: List[str]) -> List[List[float]]: |
| 74 | + """Asynchronously encode a list of documents into their corresponding embeddings. |
| 75 | +
|
| 76 | + Args: |
| 77 | + documents (List[str]): The list of documents to be encoded. |
| 78 | +
|
| 79 | + Returns: |
| 80 | + List[List[float]]: The list of embeddings, where each embedding is a list of floats. |
| 81 | + """ |
| 82 | + loop = asyncio.get_running_loop() |
| 83 | + result = await loop.run_in_executor(get_executor(), self.encode, documents) |
| 84 | + return result |
| 85 | + |
| 86 | + def encode(self, documents: List[str]) -> List[List[float]]: |
| 87 | + """Encode a list of documents into their corresponding embeddings. |
| 88 | +
|
| 89 | + Args: |
| 90 | + documents (List[str]): The list of documents to be encoded. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + List[List[float]]: The list of embeddings, where each embedding is a list of floats. |
| 94 | +
|
| 95 | + Raises: |
| 96 | + RuntimeError: If the API call fails. |
| 97 | + """ |
| 98 | + try: |
| 99 | + response = self.client.embeddings.create( |
| 100 | + model=self.embedding_model, input=documents |
| 101 | + ) |
| 102 | + embeddings = [record.embedding for record in response.data] |
| 103 | + return embeddings |
| 104 | + except Exception as e: |
| 105 | + raise RuntimeError(f"Failed to retrieve embeddings: {e}") |
0 commit comments