Skip to main content

agentai_audio/
request.rs

1//! The calls of [`SpeechGenerator`]: builders awaited with `.await`.
2
3use crate::generator::SpeechGenerator;
4use crate::provider::{AudioError, AudioFormat, SpeechResponse, VoiceId, VoicePreview};
5use std::future::{Future, IntoFuture};
6use std::pin::Pin;
7
8/// A request to speak a text, made by [`SpeechGenerator::generate`] and sent by awaiting it.
9///
10/// Unset options are not sent: the provider uses its own defaults.
11#[derive(Debug, Clone)]
12#[must_use = "a speech request does nothing until it is awaited"]
13pub struct SpeechRequest<'a> {
14    generator: &'a SpeechGenerator,
15    text: String,
16    voice: Option<VoiceId>,
17    model: Option<String>,
18    format: Option<AudioFormat>,
19    speed: Option<f64>,
20    language: Option<String>,
21    instructions: Option<String>,
22    timestamps: bool,
23    name: Option<String>,
24}
25
26impl<'a> SpeechRequest<'a> {
27    pub(crate) fn new(generator: &'a SpeechGenerator, text: String) -> Self {
28        Self {
29            generator,
30            text,
31            voice: None,
32            model: None,
33            format: None,
34            speed: None,
35            language: None,
36            instructions: None,
37            timestamps: false,
38            name: None,
39        }
40    }
41
42    /// Sets the voice. Without one the API chooses, or fails with
43    /// [`AudioError::MissingVoice`] when it needs one (OpenAI, ElevenLabs).
44    pub fn with_voice(mut self, voice: impl Into<VoiceId>) -> Self {
45        self.voice = Some(voice.into());
46        self
47    }
48
49    /// Sets the model for this call, instead of the speech model of the provider.
50    pub fn with_model(mut self, model: impl Into<String>) -> Self {
51        self.model = Some(model.into());
52        self
53    }
54
55    /// Sets the output format.
56    pub fn with_format(mut self, format: AudioFormat) -> Self {
57        self.format = Some(format);
58        self
59    }
60
61    /// Sets the speaking speed.
62    pub fn with_speed(mut self, speed: f64) -> Self {
63        self.speed = Some(speed);
64        self
65    }
66
67    /// Sets the language of the text.
68    pub fn with_language(mut self, language: impl Into<String>) -> Self {
69        self.language = Some(language.into());
70        self
71    }
72
73    /// Sets the style instructions. Providers without an equivalent ignore them.
74    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
75        self.instructions = Some(instructions.into());
76        self
77    }
78
79    /// Asks for the time of every word in [`SpeechResponse::timestamps`]. A provider that
80    /// cannot give them returns [`AudioError::Unsupported`].
81    pub fn with_timestamps(mut self, timestamps: bool) -> Self {
82        self.timestamps = timestamps;
83        self
84    }
85
86    /// Sets the file name of the audio, set as its `Media::name`. Never sent to the provider.
87    pub fn with_name(mut self, name: impl Into<String>) -> Self {
88        self.name = Some(name.into());
89        self
90    }
91
92    /// The text to speak.
93    pub fn text(&self) -> &str {
94        &self.text
95    }
96
97    /// The voice, if set.
98    pub fn voice(&self) -> Option<&str> {
99        self.voice.as_deref()
100    }
101
102    /// The model of this call, if set.
103    pub fn model(&self) -> Option<&str> {
104        self.model.as_deref()
105    }
106
107    /// The output format, if set.
108    pub fn format(&self) -> Option<AudioFormat> {
109        self.format
110    }
111
112    /// The speaking speed, if set.
113    pub fn speed(&self) -> Option<f64> {
114        self.speed
115    }
116
117    /// The language, if set.
118    pub fn language(&self) -> Option<&str> {
119        self.language.as_deref()
120    }
121
122    /// The style instructions, if set.
123    pub fn instructions(&self) -> Option<&str> {
124        self.instructions.as_deref()
125    }
126
127    /// Whether the time of every word is asked for.
128    pub fn timestamps(&self) -> bool {
129        self.timestamps
130    }
131
132    pub(crate) fn name(&self) -> Option<&str> {
133        self.name.as_deref()
134    }
135
136    /// Fails for a request with timestamps, for providers that cannot give them.
137    pub(crate) fn without_timestamps(&self) -> Result<(), AudioError> {
138        without_timestamps(self.timestamps)
139    }
140}
141
142impl<'a> IntoFuture for SpeechRequest<'a> {
143    type Output = Result<SpeechResponse, AudioError>;
144    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;
145
146    fn into_future(self) -> Self::IntoFuture {
147        Box::pin(async move { self.generator.speak(&self).await })
148    }
149}
150
151/// One turn of a dialogue: who speaks and what.
152#[derive(Debug, Clone, PartialEq, Eq)]
153#[non_exhaustive]
154pub struct DialogueTurn {
155    /// The voice that speaks the turn.
156    pub voice: VoiceId,
157    /// What the voice says.
158    pub text: String,
159}
160
161impl DialogueTurn {
162    /// Creates a turn of `voice` saying `text`.
163    pub fn new(voice: impl Into<VoiceId>, text: impl Into<String>) -> Self {
164        Self {
165            voice: voice.into(),
166            text: text.into(),
167        }
168    }
169}
170
171/// A request to speak a dialogue of several voices, made by
172/// [`SpeechGenerator::generate_dialogue`] and sent by awaiting it.
173#[derive(Debug, Clone)]
174#[must_use = "a dialogue request does nothing until it is awaited"]
175pub struct DialogueRequest<'a> {
176    generator: &'a SpeechGenerator,
177    voices: Vec<VoiceId>,
178    turns: Vec<(usize, String)>,
179    model: Option<String>,
180    format: Option<AudioFormat>,
181    speed: Option<f64>,
182    language: Option<String>,
183    timestamps: bool,
184    name: Option<String>,
185}
186
187impl<'a> DialogueRequest<'a> {
188    pub(crate) fn new(
189        generator: &'a SpeechGenerator,
190        dialogue: impl IntoIterator<Item = DialogueTurn>,
191    ) -> Self {
192        let mut voices: Vec<VoiceId> = Vec::new();
193        let turns = dialogue
194            .into_iter()
195            .map(|turn| {
196                let speaker = match voices.iter().position(|voice| *voice == turn.voice) {
197                    Some(speaker) => speaker,
198                    None => {
199                        voices.push(turn.voice);
200                        voices.len() - 1
201                    }
202                };
203                (speaker, turn.text)
204            })
205            .collect();
206        Self {
207            generator,
208            voices,
209            turns,
210            model: None,
211            format: None,
212            speed: None,
213            language: None,
214            timestamps: false,
215            name: None,
216        }
217    }
218
219    /// Sets the model for this call, instead of the dialogue model of the provider.
220    pub fn with_model(mut self, model: impl Into<String>) -> Self {
221        self.model = Some(model.into());
222        self
223    }
224
225    /// Sets the output format.
226    pub fn with_format(mut self, format: AudioFormat) -> Self {
227        self.format = Some(format);
228        self
229    }
230
231    /// Sets the speaking speed of every turn. A provider that cannot set it for a dialogue
232    /// returns [`AudioError::Unsupported`].
233    pub fn with_speed(mut self, speed: f64) -> Self {
234        self.speed = Some(speed);
235        self
236    }
237
238    /// Sets the language of the text.
239    pub fn with_language(mut self, language: impl Into<String>) -> Self {
240        self.language = Some(language.into());
241        self
242    }
243
244    /// Asks for the time of every word in [`SpeechResponse::timestamps`]. A provider that
245    /// cannot give them returns [`AudioError::Unsupported`].
246    pub fn with_timestamps(mut self, timestamps: bool) -> Self {
247        self.timestamps = timestamps;
248        self
249    }
250
251    /// Sets the file name of the audio, set as its `Media::name`. Never sent to the provider.
252    pub fn with_name(mut self, name: impl Into<String>) -> Self {
253        self.name = Some(name.into());
254        self
255    }
256
257    /// The distinct voices, in the order they first speak. A voice's index is its speaker
258    /// number in [`turns`](Self::turns).
259    pub fn voices(&self) -> &[VoiceId] {
260        &self.voices
261    }
262
263    /// Every turn as the index of its voice in [`voices`](Self::voices) and its text.
264    pub fn turns(&self) -> &[(usize, String)] {
265        &self.turns
266    }
267
268    /// The speaking speed, if set.
269    pub fn speed(&self) -> Option<f64> {
270        self.speed
271    }
272
273    /// The model of this call, if set.
274    pub fn model(&self) -> Option<&str> {
275        self.model.as_deref()
276    }
277
278    /// The output format, if set.
279    pub fn format(&self) -> Option<AudioFormat> {
280        self.format
281    }
282
283    /// The language, if set.
284    pub fn language(&self) -> Option<&str> {
285        self.language.as_deref()
286    }
287
288    /// Whether the time of every word is asked for.
289    pub fn timestamps(&self) -> bool {
290        self.timestamps
291    }
292
293    pub(crate) fn name(&self) -> Option<&str> {
294        self.name.as_deref()
295    }
296
297    /// Fails for a request with timestamps, for providers that cannot give them.
298    pub(crate) fn without_timestamps(&self) -> Result<(), AudioError> {
299        without_timestamps(self.timestamps)
300    }
301}
302
303impl<'a> IntoFuture for DialogueRequest<'a> {
304    type Output = Result<SpeechResponse, AudioError>;
305    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;
306
307    fn into_future(self) -> Self::IntoFuture {
308        Box::pin(async move { self.generator.speak_dialogue(&self).await })
309    }
310}
311
312/// A request to design voices from a description, made by [`SpeechGenerator::design_voice`]
313/// and sent by awaiting it. It returns previews to listen to.
314#[derive(Debug, Clone)]
315#[must_use = "a voice design request does nothing until it is awaited"]
316pub struct DesignVoiceRequest<'a> {
317    generator: &'a SpeechGenerator,
318    description: String,
319    text: Option<String>,
320    language: Option<String>,
321    count: usize,
322    model: Option<String>,
323}
324
325impl<'a> DesignVoiceRequest<'a> {
326    pub(crate) fn new(generator: &'a SpeechGenerator, description: String) -> Self {
327        Self {
328            generator,
329            description,
330            text: None,
331            language: None,
332            count: 1,
333            model: None,
334        }
335    }
336
337    /// Sets the text the previews say, for providers that let you choose.
338    pub fn with_text(mut self, text: impl Into<String>) -> Self {
339        self.text = Some(text.into());
340        self
341    }
342
343    /// Sets the language of the voice (a BCP-47 code such as `pl`). Fish Audio and oMLX send it;
344    /// ElevenLabs has no such setting and ignores it.
345    pub fn with_language(mut self, language: impl Into<String>) -> Self {
346        self.language = Some(language.into());
347        self
348    }
349
350    /// Sets how many previews to ask for (1 by default). A provider may return its own number.
351    pub fn with_count(mut self, count: usize) -> Self {
352        self.count = count;
353        self
354    }
355
356    /// Sets the model for this call, instead of the design model of the provider. It does not
357    /// turn on voice design for a provider without a design model.
358    pub fn with_model(mut self, model: impl Into<String>) -> Self {
359        self.model = Some(model.into());
360        self
361    }
362
363    /// The description of the voice.
364    pub fn description(&self) -> &str {
365        &self.description
366    }
367
368    /// The text of the previews, if set.
369    pub fn text(&self) -> Option<&str> {
370        self.text.as_deref()
371    }
372
373    /// The language of the voice, if set.
374    pub fn language(&self) -> Option<&str> {
375        self.language.as_deref()
376    }
377
378    /// How many previews to ask for.
379    pub fn count(&self) -> usize {
380        self.count
381    }
382
383    /// The model of this call, if set.
384    pub fn model(&self) -> Option<&str> {
385        self.model.as_deref()
386    }
387}
388
389impl<'a> IntoFuture for DesignVoiceRequest<'a> {
390    type Output = Result<Vec<VoicePreview>, AudioError>;
391    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;
392
393    fn into_future(self) -> Self::IntoFuture {
394        Box::pin(async move { self.generator.design(&self).await })
395    }
396}
397
398fn without_timestamps(timestamps: bool) -> Result<(), AudioError> {
399    if timestamps {
400        Err(AudioError::Unsupported("word timestamps"))
401    } else {
402        Ok(())
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use crate::provider::SpeechProvider;
410    use async_trait::async_trait;
411
412    struct NoProvider;
413
414    #[async_trait]
415    impl SpeechProvider for NoProvider {
416        async fn generate(&self, _: &SpeechRequest<'_>) -> Result<SpeechResponse, AudioError> {
417            unreachable!()
418        }
419    }
420
421    #[test]
422    fn dialogue_voices_are_distinct_in_order_of_first_turn() {
423        let generator = SpeechGenerator::from_provider(NoProvider);
424        let request = generator.generate_dialogue([
425            DialogueTurn::new("b", "1"),
426            DialogueTurn::new("a", "2"),
427            DialogueTurn::new("b", "3"),
428        ]);
429        assert_eq!(request.voices(), ["b", "a"]);
430        assert_eq!(
431            request.turns(),
432            [
433                (0, "1".to_string()),
434                (1, "2".to_string()),
435                (0, "3".to_string())
436            ]
437        );
438    }
439}