rig/providers/
azure.rs

1//! Azure OpenAI API client and Rig integration
2//!
3//! # Example
4//! ```
5//! use rig::providers::azure;
6//! use rig::client::CompletionClient;
7//!
8//! let client: azure::Client<reqwest::Client> = azure::Client::builder()
9//!     .api_key("test")
10//!     .azure_endpoint("test".to_string()) // add your endpoint here!
11//!     .build()?;
12//!
13//! let gpt4o = client.completion_model(azure::GPT_4O);
14//! ```
15//!
16//! ## Authentication
17//! The authentication type used for the `azure` module is [`AzureOpenAIAuth`].
18//!
19//! By default, using a type that implements `Into<String>` as the input for the client builder will turn the type into a bearer auth token.
20//! If you want to use an API key, you need to use the type specifically.
21
22use std::fmt::Debug;
23
24use super::openai::{TranscriptionResponse, send_compatible_streaming_request};
25#[cfg(feature = "image")]
26use crate::client::Nothing;
27use crate::client::{
28    self, ApiKey, Capabilities, Capable, DebugExt, Provider, ProviderBuilder, ProviderClient,
29};
30use crate::completion::GetTokenUsage;
31use crate::http_client::multipart::Part;
32use crate::http_client::{self, HttpClientExt, MultipartForm, bearer_auth_header};
33use crate::streaming::StreamingCompletionResponse;
34use crate::transcription::TranscriptionError;
35use crate::{
36    completion::{self, CompletionError, CompletionRequest},
37    embeddings::{self, EmbeddingError},
38    json_utils,
39    providers::openai,
40    telemetry::SpanCombinator,
41    transcription::{self},
42};
43use bytes::Bytes;
44use serde::{Deserialize, Serialize};
45use serde_json::json;
46// ================================================================
47// Main Azure OpenAI Client
48// ================================================================
49
50const DEFAULT_API_VERSION: &str = "2024-10-21";
51
52#[derive(Debug, Clone)]
53pub struct AzureExt {
54    endpoint: String,
55    api_version: String,
56}
57
58impl DebugExt for AzureExt {
59    fn fields(&self) -> impl Iterator<Item = (&'static str, &dyn std::fmt::Debug)> {
60        [
61            ("endpoint", (&self.endpoint as &dyn Debug)),
62            ("api_version", (&self.api_version as &dyn Debug)),
63        ]
64        .into_iter()
65    }
66}
67
68// TODO: @FayCarsons - this should be a type-safe builder,
69// but that would require extending the `ProviderBuilder`
70// to have some notion of complete vs incomplete states in a
71// given extension builder
72#[derive(Debug, Clone)]
73pub struct AzureExtBuilder {
74    endpoint: Option<String>,
75    api_version: String,
76}
77
78impl Default for AzureExtBuilder {
79    fn default() -> Self {
80        Self {
81            endpoint: None,
82            api_version: DEFAULT_API_VERSION.into(),
83        }
84    }
85}
86
87pub type Client<H = reqwest::Client> = client::Client<AzureExt, H>;
88pub type ClientBuilder<H = reqwest::Client> =
89    client::ClientBuilder<AzureExtBuilder, AzureOpenAIAuth, H>;
90
91impl Provider for AzureExt {
92    type Builder = AzureExtBuilder;
93
94    /// Verifying Azure auth without consuming tokens is not supported
95    const VERIFY_PATH: &'static str = "";
96
97    fn build<H>(
98        builder: &client::ClientBuilder<
99            Self::Builder,
100            <Self::Builder as ProviderBuilder>::ApiKey,
101            H,
102        >,
103    ) -> http_client::Result<Self> {
104        let AzureExtBuilder {
105            endpoint,
106            api_version,
107            ..
108        } = builder.ext().clone();
109
110        match endpoint {
111            Some(endpoint) => Ok(Self {
112                endpoint,
113                api_version,
114            }),
115            None => Err(http_client::Error::Instance(
116                "Azure client must be provided an endpoint prior to building".into(),
117            )),
118        }
119    }
120}
121
122impl<H> Capabilities<H> for AzureExt {
123    type Completion = Capable<CompletionModel<H>>;
124    type Embeddings = Capable<EmbeddingModel<H>>;
125    type Transcription = Capable<TranscriptionModel<H>>;
126    #[cfg(feature = "image")]
127    type ImageGeneration = Nothing;
128    #[cfg(feature = "audio")]
129    type AudioGeneration = Capable<AudioGenerationModel<H>>;
130}
131
132impl ProviderBuilder for AzureExtBuilder {
133    type Output = AzureExt;
134    type ApiKey = AzureOpenAIAuth;
135
136    const BASE_URL: &'static str = "";
137
138    fn finish<H>(
139        &self,
140        mut builder: client::ClientBuilder<Self, Self::ApiKey, H>,
141    ) -> http_client::Result<client::ClientBuilder<Self, Self::ApiKey, H>> {
142        use AzureOpenAIAuth::*;
143
144        let auth = builder.get_api_key().clone();
145
146        match auth {
147            Token(token) => bearer_auth_header(builder.headers_mut(), token.as_str())?,
148            ApiKey(key) => {
149                let k = http::HeaderName::from_static("api-key");
150                let v = http::HeaderValue::from_str(key.as_str())?;
151
152                builder.headers_mut().insert(k, v);
153            }
154        }
155
156        Ok(builder)
157    }
158}
159
160impl<H> ClientBuilder<H> {
161    /// API version to use (e.g., "2024-10-21" for GA, "2024-10-01-preview" for preview)
162    pub fn api_version(mut self, api_version: &str) -> Self {
163        self.ext_mut().api_version = api_version.into();
164
165        self
166    }
167}
168
169impl<H> client::ClientBuilder<AzureExtBuilder, AzureOpenAIAuth, H> {
170    /// Azure OpenAI endpoint URL, for example: https://{your-resource-name}.openai.azure.com
171    pub fn azure_endpoint(self, endpoint: String) -> ClientBuilder<H> {
172        self.over_ext(|AzureExtBuilder { api_version, .. }| AzureExtBuilder {
173            endpoint: Some(endpoint),
174            api_version,
175        })
176    }
177}
178
179/// The authentication type for Azure OpenAI. Can either be an API key or a token.
180/// String types will automatically be coerced to a bearer auth token by default.
181#[derive(Clone)]
182pub enum AzureOpenAIAuth {
183    ApiKey(String),
184    Token(String),
185}
186
187impl ApiKey for AzureOpenAIAuth {}
188
189impl std::fmt::Debug for AzureOpenAIAuth {
190    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191        match self {
192            Self::ApiKey(_) => write!(f, "API key <REDACTED>"),
193            Self::Token(_) => write!(f, "Token <REDACTED>"),
194        }
195    }
196}
197
198impl<S> From<S> for AzureOpenAIAuth
199where
200    S: Into<String>,
201{
202    fn from(token: S) -> Self {
203        AzureOpenAIAuth::Token(token.into())
204    }
205}
206
207impl<T> Client<T>
208where
209    T: HttpClientExt,
210{
211    fn endpoint(&self) -> &str {
212        &self.ext().endpoint
213    }
214
215    fn api_version(&self) -> &str {
216        &self.ext().api_version
217    }
218
219    fn post_embedding(&self, deployment_id: &str) -> http_client::Result<http_client::Builder> {
220        let url = format!(
221            "{}/openai/deployments/{}/embeddings?api-version={}",
222            self.endpoint(),
223            deployment_id.trim_start_matches('/'),
224            self.api_version()
225        );
226
227        self.post(&url)
228    }
229
230    #[cfg(feature = "audio")]
231    fn post_audio_generation(
232        &self,
233        deployment_id: &str,
234    ) -> http_client::Result<http_client::Builder> {
235        let url = format!(
236            "{}/openai/deployments/{}/audio/speech?api-version={}",
237            self.endpoint(),
238            deployment_id.trim_start_matches('/'),
239            self.api_version()
240        );
241
242        self.post(url)
243    }
244
245    fn post_chat_completion(
246        &self,
247        deployment_id: &str,
248    ) -> http_client::Result<http_client::Builder> {
249        let url = format!(
250            "{}/openai/deployments/{}/chat/completions?api-version={}",
251            self.endpoint(),
252            deployment_id.trim_start_matches('/'),
253            self.api_version()
254        );
255
256        self.post(&url)
257    }
258
259    fn post_transcription(&self, deployment_id: &str) -> http_client::Result<http_client::Builder> {
260        let url = format!(
261            "{}/openai/deployments/{}/audio/translations?api-version={}",
262            self.endpoint(),
263            deployment_id.trim_start_matches('/'),
264            self.api_version()
265        );
266
267        self.post(&url)
268    }
269
270    #[cfg(feature = "image")]
271    fn post_image_generation(
272        &self,
273        deployment_id: &str,
274    ) -> http_client::Result<http_client::Builder> {
275        let url = format!(
276            "{}/openai/deployments/{}/images/generations?api-version={}",
277            self.endpoint(),
278            deployment_id.trim_start_matches('/'),
279            self.api_version()
280        );
281
282        self.post(&url)
283    }
284}
285
286pub struct AzureOpenAIClientParams {
287    api_key: String,
288    version: String,
289    header: String,
290}
291
292impl ProviderClient for Client {
293    type Input = AzureOpenAIClientParams;
294
295    /// Create a new Azure OpenAI client from the `AZURE_API_KEY` or `AZURE_TOKEN`, `AZURE_API_VERSION`, and `AZURE_ENDPOINT` environment variables.
296    fn from_env() -> Self {
297        let auth = if let Ok(api_key) = std::env::var("AZURE_API_KEY") {
298            AzureOpenAIAuth::ApiKey(api_key)
299        } else if let Ok(token) = std::env::var("AZURE_TOKEN") {
300            AzureOpenAIAuth::Token(token)
301        } else {
302            panic!("Neither AZURE_API_KEY nor AZURE_TOKEN is set");
303        };
304
305        let api_version = std::env::var("AZURE_API_VERSION").expect("AZURE_API_VERSION not set");
306        let azure_endpoint = std::env::var("AZURE_ENDPOINT").expect("AZURE_ENDPOINT not set");
307
308        Self::builder()
309            .api_key(auth)
310            .azure_endpoint(azure_endpoint)
311            .api_version(&api_version)
312            .build()
313            .unwrap()
314    }
315
316    fn from_val(
317        AzureOpenAIClientParams {
318            api_key,
319            version,
320            header,
321        }: Self::Input,
322    ) -> Self {
323        let auth = AzureOpenAIAuth::ApiKey(api_key.to_string());
324
325        Self::builder()
326            .api_key(auth)
327            .azure_endpoint(header)
328            .api_version(&version)
329            .build()
330            .unwrap()
331    }
332}
333
334#[derive(Debug, Deserialize)]
335struct ApiErrorResponse {
336    message: String,
337}
338
339#[derive(Debug, Deserialize)]
340#[serde(untagged)]
341enum ApiResponse<T> {
342    Ok(T),
343    Err(ApiErrorResponse),
344}
345
346// ================================================================
347// Azure OpenAI Embedding API
348// ================================================================
349
350/// `text-embedding-3-large` embedding model
351pub const TEXT_EMBEDDING_3_LARGE: &str = "text-embedding-3-large";
352/// `text-embedding-3-small` embedding model
353pub const TEXT_EMBEDDING_3_SMALL: &str = "text-embedding-3-small";
354/// `text-embedding-ada-002` embedding model
355pub const TEXT_EMBEDDING_ADA_002: &str = "text-embedding-ada-002";
356
357fn model_dimensions_from_identifier(identifier: &str) -> Option<usize> {
358    match identifier {
359        TEXT_EMBEDDING_3_LARGE => Some(3_072),
360        TEXT_EMBEDDING_3_SMALL | TEXT_EMBEDDING_ADA_002 => Some(1_536),
361        _ => None,
362    }
363}
364
365#[derive(Debug, Deserialize)]
366pub struct EmbeddingResponse {
367    pub object: String,
368    pub data: Vec<EmbeddingData>,
369    pub model: String,
370    pub usage: Usage,
371}
372
373impl From<ApiErrorResponse> for EmbeddingError {
374    fn from(err: ApiErrorResponse) -> Self {
375        EmbeddingError::ProviderError(err.message)
376    }
377}
378
379impl From<ApiResponse<EmbeddingResponse>> for Result<EmbeddingResponse, EmbeddingError> {
380    fn from(value: ApiResponse<EmbeddingResponse>) -> Self {
381        match value {
382            ApiResponse::Ok(response) => Ok(response),
383            ApiResponse::Err(err) => Err(EmbeddingError::ProviderError(err.message)),
384        }
385    }
386}
387
388#[derive(Debug, Deserialize)]
389pub struct EmbeddingData {
390    pub object: String,
391    pub embedding: Vec<f64>,
392    pub index: usize,
393}
394
395#[derive(Clone, Debug, Deserialize)]
396pub struct Usage {
397    pub prompt_tokens: usize,
398    pub total_tokens: usize,
399}
400
401impl GetTokenUsage for Usage {
402    fn token_usage(&self) -> Option<crate::completion::Usage> {
403        let mut usage = crate::completion::Usage::new();
404
405        usage.input_tokens = self.prompt_tokens as u64;
406        usage.total_tokens = self.total_tokens as u64;
407        usage.output_tokens = usage.total_tokens - usage.input_tokens;
408
409        Some(usage)
410    }
411}
412
413impl std::fmt::Display for Usage {
414    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
415        write!(
416            f,
417            "Prompt tokens: {} Total tokens: {}",
418            self.prompt_tokens, self.total_tokens
419        )
420    }
421}
422
423#[derive(Clone)]
424pub struct EmbeddingModel<T = reqwest::Client> {
425    client: Client<T>,
426    pub model: String,
427    ndims: usize,
428}
429
430impl<T> embeddings::EmbeddingModel for EmbeddingModel<T>
431where
432    T: HttpClientExt + Default + Clone + 'static,
433{
434    const MAX_DOCUMENTS: usize = 1024;
435
436    type Client = Client<T>;
437
438    fn make(client: &Self::Client, model: impl Into<String>, dims: Option<usize>) -> Self {
439        Self::new(client.clone(), model, dims)
440    }
441
442    fn ndims(&self) -> usize {
443        self.ndims
444    }
445
446    async fn embed_texts(
447        &self,
448        documents: impl IntoIterator<Item = String>,
449    ) -> Result<Vec<embeddings::Embedding>, EmbeddingError> {
450        let documents = documents.into_iter().collect::<Vec<_>>();
451
452        let body = serde_json::to_vec(&json!({
453            "input": documents,
454        }))?;
455
456        let req = self
457            .client
458            .post_embedding(self.model.as_str())?
459            .body(body)
460            .map_err(|e| EmbeddingError::HttpError(e.into()))?;
461
462        let response = self.client.send(req).await?;
463
464        if response.status().is_success() {
465            let body: Vec<u8> = response.into_body().await?;
466            let body: ApiResponse<EmbeddingResponse> = serde_json::from_slice(&body)?;
467
468            match body {
469                ApiResponse::Ok(response) => {
470                    tracing::info!(target: "rig",
471                        "Azure embedding token usage: {}",
472                        response.usage
473                    );
474
475                    if response.data.len() != documents.len() {
476                        return Err(EmbeddingError::ResponseError(
477                            "Response data length does not match input length".into(),
478                        ));
479                    }
480
481                    Ok(response
482                        .data
483                        .into_iter()
484                        .zip(documents.into_iter())
485                        .map(|(embedding, document)| embeddings::Embedding {
486                            document,
487                            vec: embedding.embedding,
488                        })
489                        .collect())
490                }
491                ApiResponse::Err(err) => Err(EmbeddingError::ProviderError(err.message)),
492            }
493        } else {
494            let text = http_client::text(response).await?;
495            Err(EmbeddingError::ProviderError(text))
496        }
497    }
498}
499
500impl<T> EmbeddingModel<T> {
501    pub fn new(client: Client<T>, model: impl Into<String>, ndims: Option<usize>) -> Self {
502        let model = model.into();
503        let ndims = ndims
504            .or(model_dimensions_from_identifier(&model))
505            .unwrap_or_default();
506
507        Self {
508            client,
509            model,
510            ndims,
511        }
512    }
513
514    pub fn with_model(client: Client<T>, model: &str, ndims: Option<usize>) -> Self {
515        let ndims = ndims.unwrap_or_default();
516
517        Self {
518            client,
519            model: model.into(),
520            ndims,
521        }
522    }
523}
524
525// ================================================================
526// Azure OpenAI Completion API
527// ================================================================
528
529/// `o1` completion model
530pub const O1: &str = "o1";
531/// `o1-preview` completion model
532pub const O1_PREVIEW: &str = "o1-preview";
533/// `o1-mini` completion model
534pub const O1_MINI: &str = "o1-mini";
535/// `gpt-4o` completion model
536pub const GPT_4O: &str = "gpt-4o";
537/// `gpt-4o-mini` completion model
538pub const GPT_4O_MINI: &str = "gpt-4o-mini";
539/// `gpt-4o-realtime-preview` completion model
540pub const GPT_4O_REALTIME_PREVIEW: &str = "gpt-4o-realtime-preview";
541/// `gpt-4-turbo` completion model
542pub const GPT_4_TURBO: &str = "gpt-4";
543/// `gpt-4` completion model
544pub const GPT_4: &str = "gpt-4";
545/// `gpt-4-32k` completion model
546pub const GPT_4_32K: &str = "gpt-4-32k";
547/// `gpt-4-32k` completion model
548pub const GPT_4_32K_0613: &str = "gpt-4-32k";
549/// `gpt-3.5-turbo` completion model
550pub const GPT_35_TURBO: &str = "gpt-3.5-turbo";
551/// `gpt-3.5-turbo-instruct` completion model
552pub const GPT_35_TURBO_INSTRUCT: &str = "gpt-3.5-turbo-instruct";
553/// `gpt-3.5-turbo-16k` completion model
554pub const GPT_35_TURBO_16K: &str = "gpt-3.5-turbo-16k";
555
556#[derive(Debug, Serialize, Deserialize)]
557pub(super) struct AzureOpenAICompletionRequest {
558    model: String,
559    pub messages: Vec<openai::Message>,
560    #[serde(skip_serializing_if = "Option::is_none")]
561    temperature: Option<f64>,
562    #[serde(skip_serializing_if = "Vec::is_empty")]
563    tools: Vec<openai::ToolDefinition>,
564    #[serde(skip_serializing_if = "Option::is_none")]
565    tool_choice: Option<crate::providers::openrouter::ToolChoice>,
566    #[serde(flatten, skip_serializing_if = "Option::is_none")]
567    pub additional_params: Option<serde_json::Value>,
568}
569
570impl TryFrom<(&str, CompletionRequest)> for AzureOpenAICompletionRequest {
571    type Error = CompletionError;
572
573    fn try_from((model, req): (&str, CompletionRequest)) -> Result<Self, Self::Error> {
574        //FIXME: Must fix!
575        if req.tool_choice.is_some() {
576            tracing::warn!(
577                "Tool choice is currently not supported in Azure OpenAI. This should be fixed by Rig 0.25."
578            );
579        }
580
581        let mut full_history: Vec<openai::Message> = match &req.preamble {
582            Some(preamble) => vec![openai::Message::system(preamble)],
583            None => vec![],
584        };
585
586        if let Some(docs) = req.normalized_documents() {
587            let docs: Vec<openai::Message> = docs.try_into()?;
588            full_history.extend(docs);
589        }
590
591        let chat_history: Vec<openai::Message> = req
592            .chat_history
593            .clone()
594            .into_iter()
595            .map(|message| message.try_into())
596            .collect::<Result<Vec<Vec<openai::Message>>, _>>()?
597            .into_iter()
598            .flatten()
599            .collect();
600
601        full_history.extend(chat_history);
602
603        let tool_choice = req
604            .tool_choice
605            .clone()
606            .map(crate::providers::openrouter::ToolChoice::try_from)
607            .transpose()?;
608
609        Ok(Self {
610            model: model.to_string(),
611            messages: full_history,
612            temperature: req.temperature,
613            tools: req
614                .tools
615                .clone()
616                .into_iter()
617                .map(openai::ToolDefinition::from)
618                .collect::<Vec<_>>(),
619            tool_choice,
620            additional_params: req.additional_params,
621        })
622    }
623}
624
625#[derive(Clone)]
626pub struct CompletionModel<T = reqwest::Client> {
627    client: Client<T>,
628    /// Name of the model (e.g.: gpt-4o-mini)
629    pub model: String,
630}
631
632impl<T> CompletionModel<T> {
633    pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
634        Self {
635            client,
636            model: model.into(),
637        }
638    }
639}
640
641impl<T> completion::CompletionModel for CompletionModel<T>
642where
643    T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
644{
645    type Response = openai::CompletionResponse;
646    type StreamingResponse = openai::StreamingCompletionResponse;
647    type Client = Client<T>;
648
649    fn make(client: &Self::Client, model: impl Into<String>) -> Self {
650        Self::new(client.clone(), model.into())
651    }
652
653    async fn completion(
654        &self,
655        completion_request: CompletionRequest,
656    ) -> Result<completion::CompletionResponse<openai::CompletionResponse>, CompletionError> {
657        let span = if tracing::Span::current().is_disabled() {
658            info_span!(
659                target: "rig::completions",
660                "chat",
661                gen_ai.operation.name = "chat",
662                gen_ai.provider.name = "azure.openai",
663                gen_ai.request.model = self.model,
664                gen_ai.system_instructions = &completion_request.preamble,
665                gen_ai.response.id = tracing::field::Empty,
666                gen_ai.response.model = tracing::field::Empty,
667                gen_ai.usage.output_tokens = tracing::field::Empty,
668                gen_ai.usage.input_tokens = tracing::field::Empty,
669            )
670        } else {
671            tracing::Span::current()
672        };
673
674        let request =
675            AzureOpenAICompletionRequest::try_from((self.model.as_ref(), completion_request))?;
676
677        if enabled!(Level::TRACE) {
678            tracing::trace!(target: "rig::completions",
679                "Azure OpenAI completion request: {}",
680                serde_json::to_string_pretty(&request)?
681            );
682        }
683
684        let body = serde_json::to_vec(&request)?;
685
686        let req = self
687            .client
688            .post_chat_completion(&self.model)?
689            .body(body)
690            .map_err(http_client::Error::from)?;
691
692        async move {
693            let response = self.client.send::<_, Bytes>(req).await.unwrap();
694
695            let status = response.status();
696            let response_body = response.into_body().into_future().await?.to_vec();
697
698            if status.is_success() {
699                match serde_json::from_slice::<ApiResponse<openai::CompletionResponse>>(
700                    &response_body,
701                )? {
702                    ApiResponse::Ok(response) => {
703                        let span = tracing::Span::current();
704                        span.record_response_metadata(&response);
705                        span.record_token_usage(&response.usage);
706                        if enabled!(Level::TRACE) {
707                            tracing::trace!(target: "rig::completions",
708                                "Azure OpenAI completion response: {}",
709                                serde_json::to_string_pretty(&response)?
710                            );
711                        }
712                        response.try_into()
713                    }
714                    ApiResponse::Err(err) => Err(CompletionError::ProviderError(err.message)),
715                }
716            } else {
717                Err(CompletionError::ProviderError(
718                    String::from_utf8_lossy(&response_body).to_string(),
719                ))
720            }
721        }
722        .instrument(span)
723        .await
724    }
725
726    async fn stream(
727        &self,
728        completion_request: CompletionRequest,
729    ) -> Result<StreamingCompletionResponse<Self::StreamingResponse>, CompletionError> {
730        let preamble = completion_request.preamble.clone();
731        let mut request =
732            AzureOpenAICompletionRequest::try_from((self.model.as_ref(), completion_request))?;
733
734        let params = json_utils::merge(
735            request.additional_params.unwrap_or(serde_json::json!({})),
736            serde_json::json!({"stream": true, "stream_options": {"include_usage": true} }),
737        );
738
739        request.additional_params = Some(params);
740
741        if enabled!(Level::TRACE) {
742            tracing::trace!(target: "rig::completions",
743                "Azure OpenAI completion request: {}",
744                serde_json::to_string_pretty(&request)?
745            );
746        }
747
748        let body = serde_json::to_vec(&request)?;
749
750        let req = self
751            .client
752            .post_chat_completion(&self.model)?
753            .body(body)
754            .map_err(http_client::Error::from)?;
755
756        let span = if tracing::Span::current().is_disabled() {
757            info_span!(
758                target: "rig::completions",
759                "chat_streaming",
760                gen_ai.operation.name = "chat_streaming",
761                gen_ai.provider.name = "azure.openai",
762                gen_ai.request.model = self.model,
763                gen_ai.system_instructions = &preamble,
764                gen_ai.response.id = tracing::field::Empty,
765                gen_ai.response.model = tracing::field::Empty,
766                gen_ai.usage.output_tokens = tracing::field::Empty,
767                gen_ai.usage.input_tokens = tracing::field::Empty,
768            )
769        } else {
770            tracing::Span::current()
771        };
772
773        tracing_futures::Instrument::instrument(
774            send_compatible_streaming_request(self.client.clone(), req),
775            span,
776        )
777        .await
778    }
779}
780
781// ================================================================
782// Azure OpenAI Transcription API
783// ================================================================
784
785#[derive(Clone)]
786pub struct TranscriptionModel<T = reqwest::Client> {
787    client: Client<T>,
788    /// Name of the model (e.g.: gpt-3.5-turbo-1106)
789    pub model: String,
790}
791
792impl<T> TranscriptionModel<T> {
793    pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
794        Self {
795            client,
796            model: model.into(),
797        }
798    }
799}
800
801impl<T> transcription::TranscriptionModel for TranscriptionModel<T>
802where
803    T: HttpClientExt + Clone + 'static,
804{
805    type Response = TranscriptionResponse;
806    type Client = Client<T>;
807
808    fn make(client: &Self::Client, model: impl Into<String>) -> Self {
809        Self::new(client.clone(), model)
810    }
811
812    async fn transcription(
813        &self,
814        request: transcription::TranscriptionRequest,
815    ) -> Result<
816        transcription::TranscriptionResponse<Self::Response>,
817        transcription::TranscriptionError,
818    > {
819        let data = request.data;
820
821        let mut body =
822            MultipartForm::new().part(Part::bytes("file", data).filename(request.filename.clone()));
823
824        if let Some(prompt) = request.prompt {
825            body = body.text("prompt", prompt.clone());
826        }
827
828        if let Some(ref temperature) = request.temperature {
829            body = body.text("temperature", temperature.to_string());
830        }
831
832        if let Some(ref additional_params) = request.additional_params {
833            for (key, value) in additional_params
834                .as_object()
835                .expect("Additional Parameters to OpenAI Transcription should be a map")
836            {
837                body = body.text(key.to_owned(), value.to_string());
838            }
839        }
840
841        let req = self
842            .client
843            .post_transcription(&self.model)?
844            .body(body)
845            .map_err(|e| TranscriptionError::HttpError(e.into()))?;
846
847        let response = self.client.send_multipart::<Bytes>(req).await?;
848        let status = response.status();
849        let response_body = response.into_body().into_future().await?.to_vec();
850
851        if status.is_success() {
852            match serde_json::from_slice::<ApiResponse<TranscriptionResponse>>(&response_body)? {
853                ApiResponse::Ok(response) => response.try_into(),
854                ApiResponse::Err(api_error_response) => Err(TranscriptionError::ProviderError(
855                    api_error_response.message,
856                )),
857            }
858        } else {
859            Err(TranscriptionError::ProviderError(
860                String::from_utf8_lossy(&response_body).to_string(),
861            ))
862        }
863    }
864}
865
866// ================================================================
867// Azure OpenAI Image Generation API
868// ================================================================
869#[cfg(feature = "image")]
870pub use image_generation::*;
871use tracing::{Instrument, Level, enabled, info_span};
872#[cfg(feature = "image")]
873#[cfg_attr(docsrs, doc(cfg(feature = "image")))]
874mod image_generation {
875    use crate::http_client::HttpClientExt;
876    use crate::image_generation;
877    use crate::image_generation::{ImageGenerationError, ImageGenerationRequest};
878    use crate::providers::azure::{ApiResponse, Client};
879    use crate::providers::openai::ImageGenerationResponse;
880    use bytes::Bytes;
881    use serde_json::json;
882
883    #[derive(Clone)]
884    pub struct ImageGenerationModel<T = reqwest::Client> {
885        client: Client<T>,
886        pub model: String,
887    }
888
889    impl<T> image_generation::ImageGenerationModel for ImageGenerationModel<T>
890    where
891        T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
892    {
893        type Response = ImageGenerationResponse;
894
895        type Client = Client<T>;
896
897        fn make(client: &Self::Client, model: impl Into<String>) -> Self {
898            Self {
899                client: client.clone(),
900                model: model.into(),
901            }
902        }
903
904        async fn image_generation(
905            &self,
906            generation_request: ImageGenerationRequest,
907        ) -> Result<image_generation::ImageGenerationResponse<Self::Response>, ImageGenerationError>
908        {
909            let request = json!({
910                "model": self.model,
911                "prompt": generation_request.prompt,
912                "size": format!("{}x{}", generation_request.width, generation_request.height),
913                "response_format": "b64_json"
914            });
915
916            let body = serde_json::to_vec(&request)?;
917
918            let req = self
919                .client
920                .post_image_generation(&self.model)?
921                .body(body)
922                .map_err(|e| ImageGenerationError::HttpError(e.into()))?;
923
924            let response = self.client.send::<_, Bytes>(req).await?;
925            let status = response.status();
926            let response_body = response.into_body().into_future().await?.to_vec();
927
928            if !status.is_success() {
929                return Err(ImageGenerationError::ProviderError(format!(
930                    "{status}: {}",
931                    String::from_utf8_lossy(&response_body)
932                )));
933            }
934
935            match serde_json::from_slice::<ApiResponse<ImageGenerationResponse>>(&response_body)? {
936                ApiResponse::Ok(response) => response.try_into(),
937                ApiResponse::Err(err) => Err(ImageGenerationError::ProviderError(err.message)),
938            }
939        }
940    }
941}
942// ================================================================
943// Azure OpenAI Audio Generation API
944// ================================================================
945
946#[cfg(feature = "audio")]
947pub use audio_generation::*;
948
949#[cfg(feature = "audio")]
950#[cfg_attr(docsrs, doc(cfg(feature = "audio")))]
951mod audio_generation {
952    use super::Client;
953    use crate::audio_generation::{
954        self, AudioGenerationError, AudioGenerationRequest, AudioGenerationResponse,
955    };
956    use crate::http_client::HttpClientExt;
957    use bytes::Bytes;
958    use serde_json::json;
959
960    #[derive(Clone)]
961    pub struct AudioGenerationModel<T = reqwest::Client> {
962        client: Client<T>,
963        model: String,
964    }
965
966    impl<T> AudioGenerationModel<T> {
967        pub fn new(client: Client<T>, deployment_name: impl Into<String>) -> Self {
968            Self {
969                client,
970                model: deployment_name.into(),
971            }
972        }
973    }
974
975    impl<T> audio_generation::AudioGenerationModel for AudioGenerationModel<T>
976    where
977        T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
978    {
979        type Response = Bytes;
980        type Client = Client<T>;
981
982        fn make(client: &Self::Client, model: impl Into<String>) -> Self {
983            Self::new(client.clone(), model)
984        }
985
986        async fn audio_generation(
987            &self,
988            request: AudioGenerationRequest,
989        ) -> Result<AudioGenerationResponse<Self::Response>, AudioGenerationError> {
990            let request = json!({
991                "model": self.model,
992                "input": request.text,
993                "voice": request.voice,
994                "speed": request.speed,
995            });
996
997            let body = serde_json::to_vec(&request)?;
998
999            let req = self
1000                .client
1001                .post_audio_generation("/audio/speech")?
1002                .header("Content-Type", "application/json")
1003                .body(body)
1004                .map_err(|e| AudioGenerationError::HttpError(e.into()))?;
1005
1006            let response = self.client.send::<_, Bytes>(req).await?;
1007            let status = response.status();
1008            let response_body = response.into_body().into_future().await?;
1009
1010            if !status.is_success() {
1011                return Err(AudioGenerationError::ProviderError(format!(
1012                    "{status}: {}",
1013                    String::from_utf8_lossy(&response_body)
1014                )));
1015            }
1016
1017            Ok(AudioGenerationResponse {
1018                audio: response_body.to_vec(),
1019                response: response_body,
1020            })
1021        }
1022    }
1023}
1024
1025#[cfg(test)]
1026mod azure_tests {
1027    use super::*;
1028
1029    use crate::OneOrMany;
1030    use crate::client::{completion::CompletionClient, embeddings::EmbeddingsClient};
1031    use crate::completion::CompletionModel;
1032    use crate::embeddings::EmbeddingModel;
1033
1034    #[tokio::test]
1035    #[ignore]
1036    async fn test_azure_embedding() {
1037        let _ = tracing_subscriber::fmt::try_init();
1038
1039        let client = Client::<reqwest::Client>::from_env();
1040        let model = client.embedding_model(TEXT_EMBEDDING_3_SMALL);
1041        let embeddings = model
1042            .embed_texts(vec!["Hello, world!".to_string()])
1043            .await
1044            .unwrap();
1045
1046        tracing::info!("Azure embedding: {:?}", embeddings);
1047    }
1048
1049    #[tokio::test]
1050    #[ignore]
1051    async fn test_azure_completion() {
1052        let _ = tracing_subscriber::fmt::try_init();
1053
1054        let client = Client::<reqwest::Client>::from_env();
1055        let model = client.completion_model(GPT_4O_MINI);
1056        let completion = model
1057            .completion(CompletionRequest {
1058                preamble: Some("You are a helpful assistant.".to_string()),
1059                chat_history: OneOrMany::one("Hello!".into()),
1060                documents: vec![],
1061                max_tokens: Some(100),
1062                temperature: Some(0.0),
1063                tools: vec![],
1064                tool_choice: None,
1065                additional_params: None,
1066            })
1067            .await
1068            .unwrap();
1069
1070        tracing::info!("Azure completion: {:?}", completion);
1071    }
1072}