1pub 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
25pub type VoiceId = String;
28
29#[derive(Debug, Clone, PartialEq)]
31#[non_exhaustive]
32pub enum VoiceSource {
33 #[non_exhaustive]
36 Samples {
37 samples: Vec<Media>,
38 transcript: Option<String>,
39 language: Option<String>,
40 },
41 SampleId(String),
43}
44
45impl VoiceSource {
46 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[non_exhaustive]
69pub struct VoicePreview {
70 pub audio: Media,
72 pub text: Option<String>,
74 pub sample_id: Option<String>,
76 pub sample_rate: Option<u32>,
78 #[serde(default)]
80 pub language: Option<String>,
81}
82
83impl VoicePreview {
84 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 pub fn with_language(mut self, language: impl Into<String>) -> Self {
97 self.language = Some(language.into());
98 self
99 }
100
101 pub fn with_text(mut self, text: impl Into<String>) -> Self {
103 self.text = Some(text.into());
104 self
105 }
106
107 pub fn with_sample_id(mut self, id: impl Into<String>) -> Self {
109 self.sample_id = Some(id.into());
110 self
111 }
112
113 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum AudioFormat {
143 Mp3,
144 Wav,
145 Opus,
146 Flac,
147 Aac,
148 Pcm,
150}
151
152impl AudioFormat {
153 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#[derive(Debug, Clone, PartialEq)]
168#[non_exhaustive]
169pub struct SpeechResponse {
170 pub audio: Media,
172 pub id: Option<String>,
174 pub sample_rate: Option<u32>,
176 pub timestamps: Option<Vec<WordTimestamp>>,
178 pub model: Option<String>,
180}
181
182impl SpeechResponse {
183 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 pub fn with_model(mut self, model: impl Into<String>) -> Self {
196 self.model = Some(model.into());
197 self
198 }
199
200 pub fn with_id(mut self, id: impl Into<String>) -> Self {
202 self.id = Some(id.into());
203 self
204 }
205
206 pub fn with_sample_rate(mut self, sample_rate: u32) -> Self {
208 self.sample_rate = Some(sample_rate);
209 self
210 }
211
212 pub fn with_timestamps(mut self, timestamps: Vec<WordTimestamp>) -> Self {
214 self.timestamps = Some(timestamps);
215 self
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Serialize)]
221#[non_exhaustive]
222pub struct WordTimestamp {
223 pub text: String,
225 pub start: f64,
227 pub end: f64,
229}
230
231impl WordTimestamp {
232 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#[derive(Debug, Clone, PartialEq, Serialize)]
244#[non_exhaustive]
245pub struct VoiceInfo {
246 pub id: VoiceId,
248 pub name: String,
250 pub description: Option<String>,
252 pub language: Option<String>,
254 pub origin: VoiceOrigin,
256 #[serde(skip)]
259 pub preview: Option<Media>,
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
264#[serde(rename_all = "snake_case")]
265#[non_exhaustive]
266pub enum VoiceOrigin {
267 Preset,
269 Account,
271 Store,
273}
274
275impl VoiceInfo {
276 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 pub fn with_language(mut self, language: impl Into<String>) -> Self {
290 self.language = Some(language.into());
291 self
292 }
293
294 pub fn with_preview(mut self, preview: Media) -> Self {
296 self.preview = Some(preview);
297 self
298 }
299
300 pub fn with_description(mut self, description: impl Into<String>) -> Self {
302 self.description = Some(description.into());
303 self
304 }
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
309#[non_exhaustive]
310pub struct AudioModel {
311 pub id: String,
313 pub name: String,
315 pub description: Option<String>,
317 pub speech: bool,
319 pub dialogue: bool,
321 pub voice_design: bool,
323}
324
325impl AudioModel {
326 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 pub fn with_description(mut self, description: impl Into<String>) -> Self {
340 self.description = Some(description.into());
341 self
342 }
343
344 pub fn with_speech(mut self, speech: bool) -> Self {
346 self.speech = speech;
347 self
348 }
349
350 pub fn with_dialogue(mut self, dialogue: bool) -> Self {
352 self.dialogue = dialogue;
353 self
354 }
355
356 pub fn with_voice_design(mut self, voice_design: bool) -> Self {
358 self.voice_design = voice_design;
359 self
360 }
361}
362
363#[derive(Debug, Error)]
365#[non_exhaustive]
366pub enum AudioError {
367 #[error(transparent)]
369 Http(HttpError),
370 #[error("audio API error (status {status}): {message}")]
372 Api { status: u16, message: String },
373 #[error("invalid audio API response: {0}")]
375 InvalidResponse(String),
376 #[error("not supported by the audio provider: {0}")]
378 Unsupported(&'static str),
379 #[error("no audio provider named '{0}'")]
381 UnknownProvider(String),
382 #[error("the API key is missing, set {0}")]
384 MissingApiKey(&'static str),
385 #[error("cannot save the audio: {0}")]
387 Storage(#[from] StorageError),
388 #[error("no voice: the provider needs one")]
390 MissingVoice,
391 #[error("no model for {0}")]
393 MissingModel(&'static str),
394 #[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
408fn 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 pub fn is_auth(&self) -> bool {
421 matches!(
422 self,
423 Self::Api {
424 status: 401 | 403,
425 ..
426 }
427 )
428 }
429}
430
431#[async_trait]
437pub trait SpeechProvider: Send + Sync + 'static {
438 async fn generate(&self, request: &SpeechRequest<'_>) -> Result<SpeechResponse, AudioError>;
440
441 fn supports_voice_cloning(&self) -> bool {
443 false
444 }
445
446 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 fn supports_dialogue(&self) -> bool {
463 false
464 }
465
466 async fn generate_dialogue(
469 &self,
470 request: &DialogueRequest<'_>,
471 ) -> Result<SpeechResponse, AudioError> {
472 let _ = request;
473 Err(AudioError::Unsupported("dialogue"))
474 }
475
476 fn supports_voice_design(&self) -> bool {
478 false
479 }
480
481 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 async fn list_voices(&self) -> Result<Vec<VoiceInfo>, AudioError> {
496 Err(AudioError::Unsupported("listing voices"))
497 }
498
499 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}