Skip to main content

agentai_audio/provider/
mod.rs

1//! # Speech providers
2//!
3//! [`SpeechProvider`] is the interface between your code and a text-to-speech API. Each
4//! submodule implements it for one API.
5
6pub mod elevenlabs;
7pub mod fishaudio;
8mod kind;
9pub mod omlx;
10pub mod openai;
11
12pub(crate) use kind::known_capabilities;
13pub use kind::{
14    IntoSpeechProviderKind, SpeechProviderBuilder, SpeechProviderKind, speech_provider,
15};
16
17use crate::request::{DesignVoiceRequest, DialogueRequest, SpeechRequest};
18use agentai_core::message::Media;
19use agentai_core::storage::StorageError;
20use agentai_core::{HttpError, HttpResponse};
21use async_trait::async_trait;
22use serde::{Deserialize, Serialize};
23use thiserror::Error;
24
25/// The ID of a voice, as the provider names it: a preset, a voice of the account or a voice
26/// of a [`VoiceStore`](crate::VoiceStore).
27pub type VoiceId = String;
28
29/// What a voice is created from, see [`create_voice`](SpeechProvider::create_voice).
30#[derive(Debug, Clone, PartialEq)]
31#[non_exhaustive]
32pub enum VoiceSource {
33    /// Recordings to clone. `transcript` is what is said in them, `language` the language
34    /// they are spoken in (a BCP-47 code such as `pl`).
35    #[non_exhaustive]
36    Samples {
37        samples: Vec<Media>,
38        transcript: Option<String>,
39        language: Option<String>,
40    },
41    /// The ID of a designed voice preview, see [`VoicePreview::sample_id`].
42    SampleId(String),
43}
44
45impl VoiceSource {
46    /// Recordings to clone, with the text said in them if known.
47    pub fn samples(samples: Vec<Media>, transcript: Option<&str>) -> Self {
48        Self::Samples {
49            samples,
50            transcript: transcript.map(str::to_string),
51            language: None,
52        }
53    }
54
55    /// Sets the language the samples are spoken in. It does nothing for a
56    /// [`SampleId`](Self::SampleId), whose provider keeps the language itself.
57    pub fn with_language(mut self, language: impl Into<String>) -> Self {
58        if let Self::Samples { language: lang, .. } = &mut self {
59            *lang = Some(language.into());
60        }
61        self
62    }
63}
64
65/// A sample of a designed voice: listen to it, and keep it with
66/// [`create_voice`](SpeechProvider::create_voice) if you like it.
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[non_exhaustive]
69pub struct VoicePreview {
70    /// The audio of the preview.
71    pub audio: Media,
72    /// The text spoken in the preview, if the provider reports it.
73    pub text: Option<String>,
74    /// The ID that saves the preview as a voice, for providers that keep previews.
75    pub sample_id: Option<String>,
76    /// Sample rate of the audio in Hz, if known.
77    pub sample_rate: Option<u32>,
78    /// The language of the preview (a BCP-47 code such as `pl`), if known.
79    #[serde(default)]
80    pub language: Option<String>,
81}
82
83impl VoicePreview {
84    /// Creates a preview from its audio; the other fields are empty.
85    pub fn new(audio: Media) -> Self {
86        Self {
87            audio,
88            text: None,
89            sample_id: None,
90            sample_rate: None,
91            language: None,
92        }
93    }
94
95    /// Sets the language of the preview.
96    pub fn with_language(mut self, language: impl Into<String>) -> Self {
97        self.language = Some(language.into());
98        self
99    }
100
101    /// Sets the text spoken in the preview.
102    pub fn with_text(mut self, text: impl Into<String>) -> Self {
103        self.text = Some(text.into());
104        self
105    }
106
107    /// Sets the ID that saves the preview as a voice.
108    pub fn with_sample_id(mut self, id: impl Into<String>) -> Self {
109        self.sample_id = Some(id.into());
110        self
111    }
112
113    /// Sets the sample rate in Hz.
114    pub fn with_sample_rate(mut self, rate: u32) -> Self {
115        self.sample_rate = Some(rate);
116        self
117    }
118}
119
120impl From<VoicePreview> for VoiceSource {
121    fn from(preview: VoicePreview) -> Self {
122        match preview.sample_id {
123            Some(id) => Self::SampleId(id),
124            None => Self::Samples {
125                samples: vec![preview.audio],
126                transcript: preview.text,
127                language: preview.language,
128            },
129        }
130    }
131}
132
133impl From<&VoicePreview> for VoiceSource {
134    fn from(preview: &VoicePreview) -> Self {
135        preview.clone().into()
136    }
137}
138
139/// Audio file format.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum AudioFormat {
143    Mp3,
144    Wav,
145    Opus,
146    Flac,
147    Aac,
148    /// Headerless PCM; see [`SpeechResponse::sample_rate`].
149    Pcm,
150}
151
152impl AudioFormat {
153    /// MIME type of the format.
154    pub fn content_type(self) -> &'static str {
155        match self {
156            Self::Mp3 => "audio/mpeg",
157            Self::Wav => "audio/wav",
158            Self::Opus => "audio/ogg",
159            Self::Flac => "audio/flac",
160            Self::Aac => "audio/aac",
161            Self::Pcm => "audio/pcm",
162        }
163    }
164}
165
166/// The spoken audio.
167#[derive(Debug, Clone, PartialEq)]
168#[non_exhaustive]
169pub struct SpeechResponse {
170    /// The audio.
171    pub audio: Media,
172    /// ID of the audio in the storage, when it was saved.
173    pub id: Option<String>,
174    /// Sample rate in Hz, when known. Matters for headerless PCM.
175    pub sample_rate: Option<u32>,
176    /// The time of every word, when the request asked for it.
177    pub timestamps: Option<Vec<WordTimestamp>>,
178    /// The model that was sent, if any.
179    pub model: Option<String>,
180}
181
182impl SpeechResponse {
183    /// Creates a response with the audio.
184    pub fn new(audio: Media) -> Self {
185        Self {
186            audio,
187            id: None,
188            sample_rate: None,
189            timestamps: None,
190            model: None,
191        }
192    }
193
194    /// Sets the model that was sent.
195    pub fn with_model(mut self, model: impl Into<String>) -> Self {
196        self.model = Some(model.into());
197        self
198    }
199
200    /// Sets the ID in the storage.
201    pub fn with_id(mut self, id: impl Into<String>) -> Self {
202        self.id = Some(id.into());
203        self
204    }
205
206    /// Sets the sample rate.
207    pub fn with_sample_rate(mut self, sample_rate: u32) -> Self {
208        self.sample_rate = Some(sample_rate);
209        self
210    }
211
212    /// Sets the time of every word.
213    pub fn with_timestamps(mut self, timestamps: Vec<WordTimestamp>) -> Self {
214        self.timestamps = Some(timestamps);
215        self
216    }
217}
218
219/// When a word is spoken, in seconds from the start of the audio.
220#[derive(Debug, Clone, PartialEq, Serialize)]
221#[non_exhaustive]
222pub struct WordTimestamp {
223    /// The word, as the provider split the text.
224    pub text: String,
225    /// Start in seconds.
226    pub start: f64,
227    /// End in seconds.
228    pub end: f64,
229}
230
231impl WordTimestamp {
232    /// Creates a timestamp of a word.
233    pub fn new(text: impl Into<String>, start: f64, end: f64) -> Self {
234        Self {
235            text: text.into(),
236            start,
237            end,
238        }
239    }
240}
241
242/// A voice a provider offers.
243#[derive(Debug, Clone, PartialEq, Serialize)]
244#[non_exhaustive]
245pub struct VoiceInfo {
246    /// ID for [`SpeechRequest::with_voice`].
247    pub id: VoiceId,
248    /// Display name.
249    pub name: String,
250    /// Description.
251    pub description: Option<String>,
252    /// The language the voice speaks (a BCP-47 code such as `pl`), if known.
253    pub language: Option<String>,
254    /// Where the voice comes from.
255    pub origin: VoiceOrigin,
256    /// A recording of the voice to play, when the provider has one. It is never sent to a model
257    /// by the `list_voices` tool.
258    #[serde(skip)]
259    pub preview: Option<Media>,
260}
261
262/// Where a [`VoiceInfo`] comes from.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
264#[serde(rename_all = "snake_case")]
265#[non_exhaustive]
266pub enum VoiceOrigin {
267    /// A built-in voice of the provider, such as an OpenAI preset or an ElevenLabs premade voice.
268    Preset,
269    /// A voice of your account on the provider's server: cloned, designed or professional.
270    Account,
271    /// A voice of the [`VoiceStore`](crate::VoiceStore) set on the provider.
272    Store,
273}
274
275impl VoiceInfo {
276    /// Creates a voice with its ID, name and origin.
277    pub fn new(id: impl Into<String>, name: impl Into<String>, origin: VoiceOrigin) -> Self {
278        Self {
279            id: id.into(),
280            name: name.into(),
281            description: None,
282            language: None,
283            origin,
284            preview: None,
285        }
286    }
287
288    /// Sets the language the voice speaks.
289    pub fn with_language(mut self, language: impl Into<String>) -> Self {
290        self.language = Some(language.into());
291        self
292    }
293
294    /// Sets the recording of the voice to play.
295    pub fn with_preview(mut self, preview: Media) -> Self {
296        self.preview = Some(preview);
297        self
298    }
299
300    /// Sets the description.
301    pub fn with_description(mut self, description: impl Into<String>) -> Self {
302        self.description = Some(description.into());
303        self
304    }
305}
306
307/// A model of a speech provider and what it can do.
308#[derive(Debug, Clone, PartialEq, Eq)]
309#[non_exhaustive]
310pub struct AudioModel {
311    /// Name of the model in the API.
312    pub id: String,
313    /// Display name.
314    pub name: String,
315    /// Description.
316    pub description: Option<String>,
317    /// Whether the model speaks single texts.
318    pub speech: bool,
319    /// Whether the model speaks dialogues.
320    pub dialogue: bool,
321    /// Whether the model designs voices.
322    pub voice_design: bool,
323}
324
325impl AudioModel {
326    /// Creates a speech model with its ID and display name.
327    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
328        Self {
329            id: id.into(),
330            name: name.into(),
331            description: None,
332            speech: true,
333            dialogue: false,
334            voice_design: false,
335        }
336    }
337
338    /// Sets the description.
339    pub fn with_description(mut self, description: impl Into<String>) -> Self {
340        self.description = Some(description.into());
341        self
342    }
343
344    /// Sets whether the model speaks single texts.
345    pub fn with_speech(mut self, speech: bool) -> Self {
346        self.speech = speech;
347        self
348    }
349
350    /// Sets whether the model speaks dialogues.
351    pub fn with_dialogue(mut self, dialogue: bool) -> Self {
352        self.dialogue = dialogue;
353        self
354    }
355
356    /// Sets whether the model designs voices.
357    pub fn with_voice_design(mut self, voice_design: bool) -> Self {
358        self.voice_design = voice_design;
359        self
360    }
361}
362
363/// Errors of speech providers.
364#[derive(Debug, Error)]
365#[non_exhaustive]
366pub enum AudioError {
367    /// The request could not be sent or the response could not be read.
368    #[error(transparent)]
369    Http(HttpError),
370    /// The API answered with an error status.
371    #[error("audio API error (status {status}): {message}")]
372    Api { status: u16, message: String },
373    /// The API answered with something the provider cannot read.
374    #[error("invalid audio API response: {0}")]
375    InvalidResponse(String),
376    /// The provider cannot do this, for example clone voices.
377    #[error("not supported by the audio provider: {0}")]
378    Unsupported(&'static str),
379    /// No provider has this name.
380    #[error("no audio provider named '{0}'")]
381    UnknownProvider(String),
382    /// The environment variable with the API key is not set.
383    #[error("the API key is missing, set {0}")]
384    MissingApiKey(&'static str),
385    /// The audio was made but could not be saved in the storage.
386    #[error("cannot save the audio: {0}")]
387    Storage(#[from] StorageError),
388    /// The request has no voice and the provider needs one.
389    #[error("no voice: the provider needs one")]
390    MissingVoice,
391    /// The provider has no model for this kind of call, so it is off.
392    #[error("no model for {0}")]
393    MissingModel(&'static str),
394    /// The request cannot be fulfilled as given.
395    #[error("invalid audio request: {0}")]
396    InvalidRequest(String),
397}
398
399impl From<HttpError> for AudioError {
400    fn from(err: HttpError) -> Self {
401        match err {
402            HttpError::Status { status, message } => Self::Api { status, message },
403            err => Self::Http(err),
404        }
405    }
406}
407
408/// The body of a response as audio of the given type.
409fn audio_media(response: &HttpResponse, content_type: &str) -> Result<Media, AudioError> {
410    if response.body.is_empty() {
411        return Err(AudioError::InvalidResponse(
412            "the response has no audio".to_string(),
413        ));
414    }
415    Ok(Media::from_bytes(content_type, &response.body))
416}
417
418impl AudioError {
419    /// Returns `true` when the API rejected the credentials (status 401 or 403).
420    pub fn is_auth(&self) -> bool {
421        matches!(
422            self,
423            Self::Api {
424                status: 401 | 403,
425                ..
426            }
427        )
428    }
429}
430
431/// A text-to-speech API.
432///
433/// Implement [`generate`](SpeechProvider::generate); a provider that can clone voices, speak
434/// dialogues or design voices also overrides the matching `supports_*` method and the call.
435/// The model of a call is [`SpeechRequest::model`] when set, else the provider's own model.
436#[async_trait]
437pub trait SpeechProvider: Send + Sync + 'static {
438    /// Speaks a text.
439    async fn generate(&self, request: &SpeechRequest<'_>) -> Result<SpeechResponse, AudioError>;
440
441    /// Returns `true` when the provider implements [`create_voice`](SpeechProvider::create_voice).
442    fn supports_voice_cloning(&self) -> bool {
443        false
444    }
445
446    /// Creates a voice and returns its ID for [`SpeechRequest::with_voice`]: from recordings
447    /// to clone ([`VoiceSource::Samples`]; `transcript` is what is said in them, and oMLX
448    /// rejects a cloned voice without it when the voice speaks) or by keeping a designed
449    /// [`VoicePreview`] ([`VoiceSource::SampleId`]). The default implementation returns
450    /// [`AudioError::Unsupported`].
451    async fn create_voice(
452        &self,
453        name: &str,
454        source: VoiceSource,
455        description: Option<&str>,
456    ) -> Result<VoiceId, AudioError> {
457        let _ = (name, source, description);
458        Err(AudioError::Unsupported("voice cloning"))
459    }
460
461    /// Returns `true` when the provider can speak dialogues.
462    fn supports_dialogue(&self) -> bool {
463        false
464    }
465
466    /// Speaks a dialogue of several voices. The default implementation returns
467    /// [`AudioError::Unsupported`].
468    async fn generate_dialogue(
469        &self,
470        request: &DialogueRequest<'_>,
471    ) -> Result<SpeechResponse, AudioError> {
472        let _ = request;
473        Err(AudioError::Unsupported("dialogue"))
474    }
475
476    /// Returns `true` when the provider can design voices.
477    fn supports_voice_design(&self) -> bool {
478        false
479    }
480
481    /// Designs voices from a text description and returns previews to listen to and choose
482    /// from. Keep one with [`create_voice`](SpeechProvider::create_voice) (its
483    /// [`VoiceSource::SampleId`] when the preview has one). A provider may return its own
484    /// number of previews. The default implementation returns [`AudioError::Unsupported`].
485    async fn design_voice(
486        &self,
487        request: &DesignVoiceRequest<'_>,
488    ) -> Result<Vec<VoicePreview>, AudioError> {
489        let _ = request;
490        Err(AudioError::Unsupported("voice design"))
491    }
492
493    /// Lists the voices of the API. The default implementation returns
494    /// [`AudioError::Unsupported`].
495    async fn list_voices(&self) -> Result<Vec<VoiceInfo>, AudioError> {
496        Err(AudioError::Unsupported("listing voices"))
497    }
498
499    /// Lists the models of the API (see [`AudioModel`] for dialogue and voice design). ElevenLabs
500    /// lists only its text-to-speech models, so for design models see
501    /// [`SpeechProviderKind::known_models`](crate::SpeechProviderKind::known_models). The default
502    /// implementation returns [`AudioError::Unsupported`].
503    async fn list_models(&self) -> Result<Vec<AudioModel>, AudioError> {
504        Err(AudioError::Unsupported("listing models"))
505    }
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    #[test]
513    fn a_preview_with_sample_id_is_a_sample_id() {
514        let preview = VoicePreview::new(Media::from_bytes("audio/mpeg", b"A"))
515            .with_sample_id("g1")
516            .with_text("Hi");
517        assert_eq!(
518            VoiceSource::from(&preview),
519            VoiceSource::SampleId("g1".into())
520        );
521    }
522
523    #[test]
524    fn a_preview_without_sample_id_is_samples() {
525        let audio = Media::from_bytes("audio/wav", b"A");
526        let preview = VoicePreview::new(audio.clone())
527            .with_text("Hi")
528            .with_language("pl");
529        assert_eq!(
530            VoiceSource::from(preview),
531            VoiceSource::samples(vec![audio], Some("Hi")).with_language("pl")
532        );
533    }
534
535    #[tokio::test]
536    async fn simple_providers_reject_timestamps() {
537        use agentai_core::mock::MockHttp;
538        use std::sync::Arc;
539        let http = MockHttp::new(vec![]);
540        let providers: Vec<Arc<dyn SpeechProvider>> = vec![
541            Arc::new(
542                openai::OpenAiSpeechProvider::new("tts-1", "k", "http://x")
543                    .with_client(Arc::new(http.clone())),
544            ),
545            Arc::new(
546                elevenlabs::ElevenLabsProvider::new("m", "k", "http://x")
547                    .with_client(Arc::new(http.clone())),
548            ),
549            Arc::new(
550                omlx::OmlxProvider::new("m", "", "http://x").with_client(Arc::new(http.clone())),
551            ),
552        ];
553        for provider in providers {
554            let err = crate::SpeechGenerator::new(provider)
555                .generate("hi")
556                .with_voice("a")
557                .with_timestamps(true)
558                .await
559                .unwrap_err();
560            assert!(matches!(err, AudioError::Unsupported(_)), "{err}");
561        }
562        assert_eq!(http.request_count(), 0);
563    }
564}