1use 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;
46const 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#[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 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 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 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#[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 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
346pub const TEXT_EMBEDDING_3_LARGE: &str = "text-embedding-3-large";
352pub const TEXT_EMBEDDING_3_SMALL: &str = "text-embedding-3-small";
354pub 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 mut body = json!({
453 "input": documents,
454 });
455
456 if self.ndims > 0 && self.model.as_str() != TEXT_EMBEDDING_ADA_002 {
457 body["dimensions"] = json!(self.ndims);
458 }
459
460 let body = serde_json::to_vec(&body)?;
461
462 let req = self
463 .client
464 .post_embedding(self.model.as_str())?
465 .body(body)
466 .map_err(|e| EmbeddingError::HttpError(e.into()))?;
467
468 let response = self.client.send(req).await?;
469
470 if response.status().is_success() {
471 let body: Vec<u8> = response.into_body().await?;
472 let body: ApiResponse<EmbeddingResponse> = serde_json::from_slice(&body)?;
473
474 match body {
475 ApiResponse::Ok(response) => {
476 tracing::info!(target: "rig",
477 "Azure embedding token usage: {}",
478 response.usage
479 );
480
481 if response.data.len() != documents.len() {
482 return Err(EmbeddingError::ResponseError(
483 "Response data length does not match input length".into(),
484 ));
485 }
486
487 Ok(response
488 .data
489 .into_iter()
490 .zip(documents.into_iter())
491 .map(|(embedding, document)| embeddings::Embedding {
492 document,
493 vec: embedding.embedding,
494 })
495 .collect())
496 }
497 ApiResponse::Err(err) => Err(EmbeddingError::ProviderError(err.message)),
498 }
499 } else {
500 let text = http_client::text(response).await?;
501 Err(EmbeddingError::ProviderError(text))
502 }
503 }
504}
505
506impl<T> EmbeddingModel<T> {
507 pub fn new(client: Client<T>, model: impl Into<String>, ndims: Option<usize>) -> Self {
508 let model = model.into();
509 let ndims = ndims
510 .or(model_dimensions_from_identifier(&model))
511 .unwrap_or_default();
512
513 Self {
514 client,
515 model,
516 ndims,
517 }
518 }
519
520 pub fn with_model(client: Client<T>, model: &str, ndims: Option<usize>) -> Self {
521 let ndims = ndims.unwrap_or_default();
522
523 Self {
524 client,
525 model: model.into(),
526 ndims,
527 }
528 }
529}
530
531pub const O1: &str = "o1";
537pub const O1_PREVIEW: &str = "o1-preview";
539pub const O1_MINI: &str = "o1-mini";
541pub const GPT_4O: &str = "gpt-4o";
543pub const GPT_4O_MINI: &str = "gpt-4o-mini";
545pub const GPT_4O_REALTIME_PREVIEW: &str = "gpt-4o-realtime-preview";
547pub const GPT_4_TURBO: &str = "gpt-4";
549pub const GPT_4: &str = "gpt-4";
551pub const GPT_4_32K: &str = "gpt-4-32k";
553pub const GPT_4_32K_0613: &str = "gpt-4-32k";
555pub const GPT_35_TURBO: &str = "gpt-3.5-turbo";
557pub const GPT_35_TURBO_INSTRUCT: &str = "gpt-3.5-turbo-instruct";
559pub const GPT_35_TURBO_16K: &str = "gpt-3.5-turbo-16k";
561
562#[derive(Debug, Serialize, Deserialize)]
563pub(super) struct AzureOpenAICompletionRequest {
564 model: String,
565 pub messages: Vec<openai::Message>,
566 #[serde(skip_serializing_if = "Option::is_none")]
567 temperature: Option<f64>,
568 #[serde(skip_serializing_if = "Vec::is_empty")]
569 tools: Vec<openai::ToolDefinition>,
570 #[serde(skip_serializing_if = "Option::is_none")]
571 tool_choice: Option<crate::providers::openrouter::ToolChoice>,
572 #[serde(flatten, skip_serializing_if = "Option::is_none")]
573 pub additional_params: Option<serde_json::Value>,
574}
575
576impl TryFrom<(&str, CompletionRequest)> for AzureOpenAICompletionRequest {
577 type Error = CompletionError;
578
579 fn try_from((model, req): (&str, CompletionRequest)) -> Result<Self, Self::Error> {
580 if req.tool_choice.is_some() {
582 tracing::warn!(
583 "Tool choice is currently not supported in Azure OpenAI. This should be fixed by Rig 0.25."
584 );
585 }
586
587 let mut full_history: Vec<openai::Message> = match &req.preamble {
588 Some(preamble) => vec![openai::Message::system(preamble)],
589 None => vec![],
590 };
591
592 if let Some(docs) = req.normalized_documents() {
593 let docs: Vec<openai::Message> = docs.try_into()?;
594 full_history.extend(docs);
595 }
596
597 let chat_history: Vec<openai::Message> = req
598 .chat_history
599 .clone()
600 .into_iter()
601 .map(|message| message.try_into())
602 .collect::<Result<Vec<Vec<openai::Message>>, _>>()?
603 .into_iter()
604 .flatten()
605 .collect();
606
607 full_history.extend(chat_history);
608
609 let tool_choice = req
610 .tool_choice
611 .clone()
612 .map(crate::providers::openrouter::ToolChoice::try_from)
613 .transpose()?;
614
615 Ok(Self {
616 model: model.to_string(),
617 messages: full_history,
618 temperature: req.temperature,
619 tools: req
620 .tools
621 .clone()
622 .into_iter()
623 .map(openai::ToolDefinition::from)
624 .collect::<Vec<_>>(),
625 tool_choice,
626 additional_params: req.additional_params,
627 })
628 }
629}
630
631#[derive(Clone)]
632pub struct CompletionModel<T = reqwest::Client> {
633 client: Client<T>,
634 pub model: String,
636}
637
638impl<T> CompletionModel<T> {
639 pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
640 Self {
641 client,
642 model: model.into(),
643 }
644 }
645}
646
647impl<T> completion::CompletionModel for CompletionModel<T>
648where
649 T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
650{
651 type Response = openai::CompletionResponse;
652 type StreamingResponse = openai::StreamingCompletionResponse;
653 type Client = Client<T>;
654
655 fn make(client: &Self::Client, model: impl Into<String>) -> Self {
656 Self::new(client.clone(), model.into())
657 }
658
659 async fn completion(
660 &self,
661 completion_request: CompletionRequest,
662 ) -> Result<completion::CompletionResponse<openai::CompletionResponse>, CompletionError> {
663 let span = if tracing::Span::current().is_disabled() {
664 info_span!(
665 target: "rig::completions",
666 "chat",
667 gen_ai.operation.name = "chat",
668 gen_ai.provider.name = "azure.openai",
669 gen_ai.request.model = self.model,
670 gen_ai.system_instructions = &completion_request.preamble,
671 gen_ai.response.id = tracing::field::Empty,
672 gen_ai.response.model = tracing::field::Empty,
673 gen_ai.usage.output_tokens = tracing::field::Empty,
674 gen_ai.usage.input_tokens = tracing::field::Empty,
675 )
676 } else {
677 tracing::Span::current()
678 };
679
680 let request =
681 AzureOpenAICompletionRequest::try_from((self.model.as_ref(), completion_request))?;
682
683 if enabled!(Level::TRACE) {
684 tracing::trace!(target: "rig::completions",
685 "Azure OpenAI completion request: {}",
686 serde_json::to_string_pretty(&request)?
687 );
688 }
689
690 let body = serde_json::to_vec(&request)?;
691
692 let req = self
693 .client
694 .post_chat_completion(&self.model)?
695 .body(body)
696 .map_err(http_client::Error::from)?;
697
698 async move {
699 let response = self.client.send::<_, Bytes>(req).await?;
700
701 let status = response.status();
702 let response_body = response.into_body().into_future().await?.to_vec();
703
704 if status.is_success() {
705 match serde_json::from_slice::<ApiResponse<openai::CompletionResponse>>(
706 &response_body,
707 )? {
708 ApiResponse::Ok(response) => {
709 let span = tracing::Span::current();
710 span.record_response_metadata(&response);
711 span.record_token_usage(&response.usage);
712 if enabled!(Level::TRACE) {
713 tracing::trace!(target: "rig::completions",
714 "Azure OpenAI completion response: {}",
715 serde_json::to_string_pretty(&response)?
716 );
717 }
718 response.try_into()
719 }
720 ApiResponse::Err(err) => Err(CompletionError::ProviderError(err.message)),
721 }
722 } else {
723 Err(CompletionError::ProviderError(
724 String::from_utf8_lossy(&response_body).to_string(),
725 ))
726 }
727 }
728 .instrument(span)
729 .await
730 }
731
732 async fn stream(
733 &self,
734 completion_request: CompletionRequest,
735 ) -> Result<StreamingCompletionResponse<Self::StreamingResponse>, CompletionError> {
736 let preamble = completion_request.preamble.clone();
737 let mut request =
738 AzureOpenAICompletionRequest::try_from((self.model.as_ref(), completion_request))?;
739
740 let params = json_utils::merge(
741 request.additional_params.unwrap_or(serde_json::json!({})),
742 serde_json::json!({"stream": true, "stream_options": {"include_usage": true} }),
743 );
744
745 request.additional_params = Some(params);
746
747 if enabled!(Level::TRACE) {
748 tracing::trace!(target: "rig::completions",
749 "Azure OpenAI completion request: {}",
750 serde_json::to_string_pretty(&request)?
751 );
752 }
753
754 let body = serde_json::to_vec(&request)?;
755
756 let req = self
757 .client
758 .post_chat_completion(&self.model)?
759 .body(body)
760 .map_err(http_client::Error::from)?;
761
762 let span = if tracing::Span::current().is_disabled() {
763 info_span!(
764 target: "rig::completions",
765 "chat_streaming",
766 gen_ai.operation.name = "chat_streaming",
767 gen_ai.provider.name = "azure.openai",
768 gen_ai.request.model = self.model,
769 gen_ai.system_instructions = &preamble,
770 gen_ai.response.id = tracing::field::Empty,
771 gen_ai.response.model = tracing::field::Empty,
772 gen_ai.usage.output_tokens = tracing::field::Empty,
773 gen_ai.usage.input_tokens = tracing::field::Empty,
774 )
775 } else {
776 tracing::Span::current()
777 };
778
779 tracing_futures::Instrument::instrument(
780 send_compatible_streaming_request(self.client.clone(), req),
781 span,
782 )
783 .await
784 }
785}
786
787#[derive(Clone)]
792pub struct TranscriptionModel<T = reqwest::Client> {
793 client: Client<T>,
794 pub model: String,
796}
797
798impl<T> TranscriptionModel<T> {
799 pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
800 Self {
801 client,
802 model: model.into(),
803 }
804 }
805}
806
807impl<T> transcription::TranscriptionModel for TranscriptionModel<T>
808where
809 T: HttpClientExt + Clone + 'static,
810{
811 type Response = TranscriptionResponse;
812 type Client = Client<T>;
813
814 fn make(client: &Self::Client, model: impl Into<String>) -> Self {
815 Self::new(client.clone(), model)
816 }
817
818 async fn transcription(
819 &self,
820 request: transcription::TranscriptionRequest,
821 ) -> Result<
822 transcription::TranscriptionResponse<Self::Response>,
823 transcription::TranscriptionError,
824 > {
825 let data = request.data;
826
827 let mut body =
828 MultipartForm::new().part(Part::bytes("file", data).filename(request.filename.clone()));
829
830 if let Some(prompt) = request.prompt {
831 body = body.text("prompt", prompt.clone());
832 }
833
834 if let Some(ref temperature) = request.temperature {
835 body = body.text("temperature", temperature.to_string());
836 }
837
838 if let Some(ref additional_params) = request.additional_params {
839 for (key, value) in additional_params
840 .as_object()
841 .expect("Additional Parameters to OpenAI Transcription should be a map")
842 {
843 body = body.text(key.to_owned(), value.to_string());
844 }
845 }
846
847 let req = self
848 .client
849 .post_transcription(&self.model)?
850 .body(body)
851 .map_err(|e| TranscriptionError::HttpError(e.into()))?;
852
853 let response = self.client.send_multipart::<Bytes>(req).await?;
854 let status = response.status();
855 let response_body = response.into_body().into_future().await?.to_vec();
856
857 if status.is_success() {
858 match serde_json::from_slice::<ApiResponse<TranscriptionResponse>>(&response_body)? {
859 ApiResponse::Ok(response) => response.try_into(),
860 ApiResponse::Err(api_error_response) => Err(TranscriptionError::ProviderError(
861 api_error_response.message,
862 )),
863 }
864 } else {
865 Err(TranscriptionError::ProviderError(
866 String::from_utf8_lossy(&response_body).to_string(),
867 ))
868 }
869 }
870}
871
872#[cfg(feature = "image")]
876pub use image_generation::*;
877use tracing::{Instrument, Level, enabled, info_span};
878#[cfg(feature = "image")]
879#[cfg_attr(docsrs, doc(cfg(feature = "image")))]
880mod image_generation {
881 use crate::http_client::HttpClientExt;
882 use crate::image_generation;
883 use crate::image_generation::{ImageGenerationError, ImageGenerationRequest};
884 use crate::providers::azure::{ApiResponse, Client};
885 use crate::providers::openai::ImageGenerationResponse;
886 use bytes::Bytes;
887 use serde_json::json;
888
889 #[derive(Clone)]
890 pub struct ImageGenerationModel<T = reqwest::Client> {
891 client: Client<T>,
892 pub model: String,
893 }
894
895 impl<T> image_generation::ImageGenerationModel for ImageGenerationModel<T>
896 where
897 T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
898 {
899 type Response = ImageGenerationResponse;
900
901 type Client = Client<T>;
902
903 fn make(client: &Self::Client, model: impl Into<String>) -> Self {
904 Self {
905 client: client.clone(),
906 model: model.into(),
907 }
908 }
909
910 async fn image_generation(
911 &self,
912 generation_request: ImageGenerationRequest,
913 ) -> Result<image_generation::ImageGenerationResponse<Self::Response>, ImageGenerationError>
914 {
915 let request = json!({
916 "model": self.model,
917 "prompt": generation_request.prompt,
918 "size": format!("{}x{}", generation_request.width, generation_request.height),
919 "response_format": "b64_json"
920 });
921
922 let body = serde_json::to_vec(&request)?;
923
924 let req = self
925 .client
926 .post_image_generation(&self.model)?
927 .body(body)
928 .map_err(|e| ImageGenerationError::HttpError(e.into()))?;
929
930 let response = self.client.send::<_, Bytes>(req).await?;
931 let status = response.status();
932 let response_body = response.into_body().into_future().await?.to_vec();
933
934 if !status.is_success() {
935 return Err(ImageGenerationError::ProviderError(format!(
936 "{status}: {}",
937 String::from_utf8_lossy(&response_body)
938 )));
939 }
940
941 match serde_json::from_slice::<ApiResponse<ImageGenerationResponse>>(&response_body)? {
942 ApiResponse::Ok(response) => response.try_into(),
943 ApiResponse::Err(err) => Err(ImageGenerationError::ProviderError(err.message)),
944 }
945 }
946 }
947}
948#[cfg(feature = "audio")]
953pub use audio_generation::*;
954
955#[cfg(feature = "audio")]
956#[cfg_attr(docsrs, doc(cfg(feature = "audio")))]
957mod audio_generation {
958 use super::Client;
959 use crate::audio_generation::{
960 self, AudioGenerationError, AudioGenerationRequest, AudioGenerationResponse,
961 };
962 use crate::http_client::HttpClientExt;
963 use bytes::Bytes;
964 use serde_json::json;
965
966 #[derive(Clone)]
967 pub struct AudioGenerationModel<T = reqwest::Client> {
968 client: Client<T>,
969 model: String,
970 }
971
972 impl<T> AudioGenerationModel<T> {
973 pub fn new(client: Client<T>, deployment_name: impl Into<String>) -> Self {
974 Self {
975 client,
976 model: deployment_name.into(),
977 }
978 }
979 }
980
981 impl<T> audio_generation::AudioGenerationModel for AudioGenerationModel<T>
982 where
983 T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
984 {
985 type Response = Bytes;
986 type Client = Client<T>;
987
988 fn make(client: &Self::Client, model: impl Into<String>) -> Self {
989 Self::new(client.clone(), model)
990 }
991
992 async fn audio_generation(
993 &self,
994 request: AudioGenerationRequest,
995 ) -> Result<AudioGenerationResponse<Self::Response>, AudioGenerationError> {
996 let request = json!({
997 "model": self.model,
998 "input": request.text,
999 "voice": request.voice,
1000 "speed": request.speed,
1001 });
1002
1003 let body = serde_json::to_vec(&request)?;
1004
1005 let req = self
1006 .client
1007 .post_audio_generation("/audio/speech")?
1008 .header("Content-Type", "application/json")
1009 .body(body)
1010 .map_err(|e| AudioGenerationError::HttpError(e.into()))?;
1011
1012 let response = self.client.send::<_, Bytes>(req).await?;
1013 let status = response.status();
1014 let response_body = response.into_body().into_future().await?;
1015
1016 if !status.is_success() {
1017 return Err(AudioGenerationError::ProviderError(format!(
1018 "{status}: {}",
1019 String::from_utf8_lossy(&response_body)
1020 )));
1021 }
1022
1023 Ok(AudioGenerationResponse {
1024 audio: response_body.to_vec(),
1025 response: response_body,
1026 })
1027 }
1028 }
1029}
1030
1031#[cfg(test)]
1032mod azure_tests {
1033 use super::*;
1034
1035 use crate::OneOrMany;
1036 use crate::client::{completion::CompletionClient, embeddings::EmbeddingsClient};
1037 use crate::completion::CompletionModel;
1038 use crate::embeddings::EmbeddingModel;
1039
1040 #[tokio::test]
1041 #[ignore]
1042 async fn test_azure_embedding() {
1043 let _ = tracing_subscriber::fmt::try_init();
1044
1045 let client = Client::<reqwest::Client>::from_env();
1046 let model = client.embedding_model(TEXT_EMBEDDING_3_SMALL);
1047 let embeddings = model
1048 .embed_texts(vec!["Hello, world!".to_string()])
1049 .await
1050 .unwrap();
1051
1052 tracing::info!("Azure embedding: {:?}", embeddings);
1053 }
1054
1055 #[tokio::test]
1056 #[ignore]
1057 async fn test_azure_embedding_dimensions() {
1058 let _ = tracing_subscriber::fmt::try_init();
1059
1060 let ndims = 256;
1061 let client = Client::<reqwest::Client>::from_env();
1062 let model = client.embedding_model_with_ndims(TEXT_EMBEDDING_3_SMALL, ndims);
1063 let embedding = model.embed_text("Hello, world!").await.unwrap();
1064
1065 assert!(embedding.vec.len() == ndims);
1066
1067 tracing::info!("Azure dimensions embedding: {:?}", embedding);
1068 }
1069
1070 #[tokio::test]
1071 #[ignore]
1072 async fn test_azure_completion() {
1073 let _ = tracing_subscriber::fmt::try_init();
1074
1075 let client = Client::<reqwest::Client>::from_env();
1076 let model = client.completion_model(GPT_4O_MINI);
1077 let completion = model
1078 .completion(CompletionRequest {
1079 preamble: Some("You are a helpful assistant.".to_string()),
1080 chat_history: OneOrMany::one("Hello!".into()),
1081 documents: vec![],
1082 max_tokens: Some(100),
1083 temperature: Some(0.0),
1084 tools: vec![],
1085 tool_choice: None,
1086 additional_params: None,
1087 })
1088 .await
1089 .unwrap();
1090
1091 tracing::info!("Azure completion: {:?}", completion);
1092 }
1093}