|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use anyhow::Result; |
| 4 | +use async_trait::async_trait; |
| 5 | +use reqwest::Client; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | +use tabby_inference::Embedding; |
| 8 | + |
| 9 | +use crate::AZURE_API_VERSION; |
| 10 | + |
| 11 | +/// `AzureEmbeddingEngine` is responsible for interacting with Azure's Embedding API. |
| 12 | +/// |
| 13 | +/// **Note**: Currently, this implementation only supports the OpenAI API and specific API versions. |
| 14 | +#[derive(Clone)] |
| 15 | +pub struct AzureEmbeddingEngine { |
| 16 | + client: Arc<Client>, |
| 17 | + api_endpoint: String, |
| 18 | + api_key: String, |
| 19 | +} |
| 20 | + |
| 21 | +/// Structure representing the request body for embedding. |
| 22 | +#[derive(Debug, Serialize)] |
| 23 | +struct EmbeddingRequest { |
| 24 | + input: String, |
| 25 | +} |
| 26 | + |
| 27 | +/// Structure representing the response from the embedding API. |
| 28 | +#[derive(Debug, Deserialize)] |
| 29 | +struct EmbeddingResponse { |
| 30 | + data: Vec<Data>, |
| 31 | +} |
| 32 | + |
| 33 | +/// Structure representing individual embedding data. |
| 34 | +#[derive(Debug, Deserialize)] |
| 35 | +struct Data { |
| 36 | + embedding: Vec<f32>, |
| 37 | +} |
| 38 | + |
| 39 | +impl AzureEmbeddingEngine { |
| 40 | + /// Creates a new instance of `AzureEmbeddingEngine`. |
| 41 | + /// |
| 42 | + /// **Note**: Currently, this implementation only supports the OpenAI API and specific API versions. |
| 43 | + /// |
| 44 | + /// # Parameters |
| 45 | + /// |
| 46 | + /// - `api_endpoint`: The base URL of the Azure Embedding API. |
| 47 | + /// - `model_name`: The name of the deployed model, used to construct the deployment ID. |
| 48 | + /// - `api_key`: Optional API key for authentication. |
| 49 | + /// - `api_version`: Optional API version, defaults to "2023-05-15". |
| 50 | + /// |
| 51 | + /// # Returns |
| 52 | + /// |
| 53 | + /// A boxed instance that implements the `Embedding` trait. |
| 54 | + pub fn create( |
| 55 | + api_endpoint: &str, |
| 56 | + model_name: &str, |
| 57 | + api_key: Option<&str>, |
| 58 | + ) -> Box<dyn Embedding> { |
| 59 | + let client = Client::new(); |
| 60 | + let deployment_id = model_name; |
| 61 | + // Construct the full endpoint URL for the Azure Embedding API |
| 62 | + let azure_endpoint = format!( |
| 63 | + "{}/openai/deployments/{}/embeddings", |
| 64 | + api_endpoint.trim_end_matches('/'), |
| 65 | + deployment_id |
| 66 | + ); |
| 67 | + |
| 68 | + Box::new(Self { |
| 69 | + client: Arc::new(client), |
| 70 | + api_endpoint: azure_endpoint, |
| 71 | + api_key: api_key.unwrap_or_default().to_owned(), |
| 72 | + }) |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +#[async_trait] |
| 77 | +impl Embedding for AzureEmbeddingEngine { |
| 78 | + /// Generates an embedding vector for the given prompt. |
| 79 | + /// |
| 80 | + /// **Note**: Currently, this implementation only supports the OpenAI API and specific API versions. |
| 81 | + /// |
| 82 | + /// # Parameters |
| 83 | + /// |
| 84 | + /// - `prompt`: The input text to generate embeddings for. |
| 85 | + /// |
| 86 | + /// # Returns |
| 87 | + /// |
| 88 | + /// A `Result` containing the embedding vector or an error. |
| 89 | + async fn embed(&self, prompt: &str) -> Result<Vec<f32>> { |
| 90 | + // Clone all necessary fields to ensure thread safety across await points |
| 91 | + let api_endpoint = self.api_endpoint.clone(); |
| 92 | + let api_key = self.api_key.clone(); |
| 93 | + let api_version = AZURE_API_VERSION.to_string(); |
| 94 | + let request = EmbeddingRequest { |
| 95 | + input: prompt.to_owned(), |
| 96 | + }; |
| 97 | + |
| 98 | + // Send a POST request to the Azure Embedding API |
| 99 | + let response = self |
| 100 | + .client |
| 101 | + .post(&api_endpoint) |
| 102 | + .query(&[("api-version", &api_version)]) |
| 103 | + .header("api-key", &api_key) |
| 104 | + .header("Content-Type", "application/json") |
| 105 | + .json(&request) |
| 106 | + .send() |
| 107 | + .await?; |
| 108 | + |
| 109 | + // Check if the response status indicates success |
| 110 | + if !response.status().is_success() { |
| 111 | + let error_text = response.text().await?; |
| 112 | + anyhow::bail!("Azure API error: {}", error_text); |
| 113 | + } |
| 114 | + |
| 115 | + // Deserialize the response body into `EmbeddingResponse` |
| 116 | + let embedding_response: EmbeddingResponse = response.json().await?; |
| 117 | + embedding_response |
| 118 | + .data |
| 119 | + .first() |
| 120 | + .map(|data| data.embedding.clone()) |
| 121 | + .ok_or_else(|| anyhow::anyhow!("No embedding data received")) |
| 122 | + } |
| 123 | +} |
0 commit comments