|
| 1 | +""" |
| 2 | +Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +Licensed under the MIT License. |
| 4 | +""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +from datetime import datetime |
| 8 | +from logging import Logger |
| 9 | +from operator import attrgetter |
| 10 | +from typing import List, Union |
| 11 | + |
| 12 | +import openai |
| 13 | + |
| 14 | +from teams.ai.embeddings.azure_openai_embeddings_options import ( |
| 15 | + AzureOpenAIEmbeddingsOptions, |
| 16 | +) |
| 17 | +from teams.ai.embeddings.embeddings_model import EmbeddingsModel |
| 18 | +from teams.ai.embeddings.embeddings_response import EmbeddingsResponse |
| 19 | + |
| 20 | + |
| 21 | +class AzureOpenAIEmbeddings(EmbeddingsModel): |
| 22 | + """ |
| 23 | + A `EmbeddingsModel` for calling the AzureOpenAI hosted model. |
| 24 | + """ |
| 25 | + |
| 26 | + _user_agent = "@microsoft/teams-ai-v1" |
| 27 | + _log: Logger |
| 28 | + |
| 29 | + options: AzureOpenAIEmbeddingsOptions |
| 30 | + "Options the client was configured with." |
| 31 | + |
| 32 | + def __init__(self, options: AzureOpenAIEmbeddingsOptions, log=Logger("teams.ai")) -> None: |
| 33 | + """ |
| 34 | + Creates a new `AzureOpenAIEmbeddings` instance. |
| 35 | +
|
| 36 | + Args: |
| 37 | + options (AzureOpenAIEmbeddingsOptions): Options for configuring the embeddings client. |
| 38 | + log (Logger): Logger to use. |
| 39 | + """ |
| 40 | + |
| 41 | + self.options = options |
| 42 | + self._log = log |
| 43 | + |
| 44 | + if not self.options.retry_policy: |
| 45 | + self.options.retry_policy = [2, 5] |
| 46 | + if not self.options.azure_api_version: |
| 47 | + self.options.azure_api_version = "2023-05-15" |
| 48 | + |
| 49 | + endpoint = self.options.azure_endpoint.strip() |
| 50 | + if endpoint[-1] == "/": |
| 51 | + endpoint = endpoint[0 : (len(endpoint) - 1)] |
| 52 | + |
| 53 | + if not endpoint.lower().startswith("https://"): |
| 54 | + raise ValueError( |
| 55 | + f""" |
| 56 | + Client created with an invalid endpoint of \"{endpoint}\". |
| 57 | + The endpoint must be a valid HTTPS url. |
| 58 | + """ |
| 59 | + ) |
| 60 | + |
| 61 | + self.options.azure_endpoint = endpoint |
| 62 | + |
| 63 | + async def create_embeddings( |
| 64 | + self, inputs: Union[str, List[str], List[int], List[List[int]]], retry_count=0 |
| 65 | + ) -> EmbeddingsResponse: |
| 66 | + """ |
| 67 | + Creates embeddings for the given inputs. |
| 68 | +
|
| 69 | + Args: |
| 70 | + inputs(Union[str, List[str]]): Text inputs to create embeddings for. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + EmbeddingsResponse: A status and embeddings/message when an error occurs. |
| 74 | + """ |
| 75 | + |
| 76 | + if self.options.log_requests: |
| 77 | + self._log.info("Embeddings REQUEST: inputs=%s", inputs) |
| 78 | + |
| 79 | + if not self.options.request_config: |
| 80 | + self.options.request_config = {"api-key": self.options.azure_api_key} |
| 81 | + else: |
| 82 | + self.options.request_config.update({"api-key": self.options.azure_api_key}) |
| 83 | + |
| 84 | + if not self.options.request_config.get("Content-Type"): |
| 85 | + self.options.request_config.update({"Content-Type": "application/json"}) |
| 86 | + |
| 87 | + if not self.options.request_config.get("User-Agent"): |
| 88 | + self.options.request_config.update({"User-Agent": self._user_agent}) |
| 89 | + |
| 90 | + client = openai.AsyncAzureOpenAI( |
| 91 | + api_key=self.options.azure_api_key, |
| 92 | + api_version=self.options.azure_api_version, |
| 93 | + azure_endpoint=self.options.azure_endpoint, |
| 94 | + default_headers=self.options.request_config, |
| 95 | + ) |
| 96 | + try: |
| 97 | + start_time = datetime.now() |
| 98 | + res = await client.embeddings.create(input=inputs, model=self.options.azure_deployment) |
| 99 | + |
| 100 | + data = list(map(attrgetter("embedding"), sorted(res.data, key=lambda x: x.index))) |
| 101 | + |
| 102 | + if self.options.log_requests: |
| 103 | + duration = datetime.now() - start_time |
| 104 | + self._log.info( |
| 105 | + "Embeddings SUCCEEDED: duration=%s response=%s", duration.total_seconds, data |
| 106 | + ) |
| 107 | + |
| 108 | + return EmbeddingsResponse(status="success", output=data) |
| 109 | + except openai.RateLimitError: |
| 110 | + if self.options.retry_policy: |
| 111 | + if retry_count < len(self.options.retry_policy): |
| 112 | + delay = self.options.retry_policy[retry_count] |
| 113 | + await asyncio.sleep(delay) |
| 114 | + return await self.create_embeddings(inputs, retry_count + 1) |
| 115 | + return EmbeddingsResponse( |
| 116 | + status="rate_limited", output="The embeddings API returned a rate limit error." |
| 117 | + ) |
| 118 | + except openai.APIError as err: |
| 119 | + return EmbeddingsResponse( |
| 120 | + status="error", |
| 121 | + output=f"The embeddings API returned an error status of {err.code}: {err.message}", |
| 122 | + ) |
0 commit comments