async_openai/audio/
speech.rs

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