async_openai/audio/
speech.rs

1use crate::{
2    config::Config,
3    error::OpenAIError,
4    types::audio::{CreateSpeechRequest, CreateSpeechResponse, SpeechResponseStream},
5    Client, RequestOptions,
6};
7
8pub struct Speech<'c, C: Config> {
9    client: &'c Client<C>,
10    pub(crate) request_options: RequestOptions,
11}
12
13impl<'c, C: Config> Speech<'c, C> {
14    pub fn new(client: &'c Client<C>) -> Self {
15        Self {
16            client,
17            request_options: RequestOptions::new(),
18        }
19    }
20
21    /// Generates audio from the input text.
22    pub async fn create(
23        &self,
24        request: CreateSpeechRequest,
25    ) -> Result<CreateSpeechResponse, OpenAIError> {
26        let (bytes, _headers) = self
27            .client
28            .post_raw("/audio/speech", request, &self.request_options)
29            .await?;
30
31        Ok(CreateSpeechResponse { bytes })
32    }
33
34    /// Generates audio from the input text in SSE stream format.
35    #[crate::byot(
36        T0 = serde::Serialize,
37        R = serde::de::DeserializeOwned,
38        stream = "true",
39        where_clause = "R: std::marker::Send + 'static"
40    )]
41    #[allow(unused_mut)]
42    pub async fn create_stream(
43        &self,
44        mut request: CreateSpeechRequest,
45    ) -> Result<SpeechResponseStream, OpenAIError> {
46        #[cfg(not(feature = "byot"))]
47        {
48            use crate::types::audio::StreamFormat;
49            if let Some(stream_format) = request.stream_format {
50                if stream_format != StreamFormat::SSE {
51                    return Err(OpenAIError::InvalidArgument(
52                        "When stream_format is not SSE, use Audio::speech".into(),
53                    ));
54                }
55            }
56
57            request.stream_format = Some(StreamFormat::SSE);
58        }
59        Ok(self
60            .client
61            .post_stream("/audio/speech", request, &self.request_options)
62            .await)
63    }
64}