pub mod elevenlabs;
pub mod fishaudio;
mod kind;
pub mod omlx;
pub mod openai;
pub(crate) use kind::known_capabilities;
pub use kind::{
IntoSpeechProviderKind, SpeechProviderBuilder, SpeechProviderKind, speech_provider,
};
use crate::request::{DesignVoiceRequest, DialogueRequest, SpeechRequest};
use agentai_core::message::Media;
use agentai_core::storage::StorageError;
use agentai_core::{HttpError, HttpResponse};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use thiserror::Error;
pub type VoiceId = String;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum VoiceSource {
#[non_exhaustive]
Samples {
samples: Vec<Media>,
transcript: Option<String>,
language: Option<String>,
},
SampleId(String),
}
impl VoiceSource {
pub fn samples(samples: Vec<Media>, transcript: Option<&str>) -> Self {
Self::Samples {
samples,
transcript: transcript.map(str::to_string),
language: None,
}
}
pub fn with_language(mut self, language: impl Into<String>) -> Self {
if let Self::Samples { language: lang, .. } = &mut self {
*lang = Some(language.into());
}
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VoicePreview {
pub audio: Media,
pub text: Option<String>,
pub sample_id: Option<String>,
pub sample_rate: Option<u32>,
#[serde(default)]
pub language: Option<String>,
}
impl VoicePreview {
pub fn new(audio: Media) -> Self {
Self {
audio,
text: None,
sample_id: None,
sample_rate: None,
language: None,
}
}
pub fn with_language(mut self, language: impl Into<String>) -> Self {
self.language = Some(language.into());
self
}
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn with_sample_id(mut self, id: impl Into<String>) -> Self {
self.sample_id = Some(id.into());
self
}
pub fn with_sample_rate(mut self, rate: u32) -> Self {
self.sample_rate = Some(rate);
self
}
}
impl From<VoicePreview> for VoiceSource {
fn from(preview: VoicePreview) -> Self {
match preview.sample_id {
Some(id) => Self::SampleId(id),
None => Self::Samples {
samples: vec![preview.audio],
transcript: preview.text,
language: preview.language,
},
}
}
}
impl From<&VoicePreview> for VoiceSource {
fn from(preview: &VoicePreview) -> Self {
preview.clone().into()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AudioFormat {
Mp3,
Wav,
Opus,
Flac,
Aac,
Pcm,
}
impl AudioFormat {
pub fn content_type(self) -> &'static str {
match self {
Self::Mp3 => "audio/mpeg",
Self::Wav => "audio/wav",
Self::Opus => "audio/ogg",
Self::Flac => "audio/flac",
Self::Aac => "audio/aac",
Self::Pcm => "audio/pcm",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SpeechResponse {
pub audio: Media,
pub id: Option<String>,
pub sample_rate: Option<u32>,
pub timestamps: Option<Vec<WordTimestamp>>,
pub model: Option<String>,
}
impl SpeechResponse {
pub fn new(audio: Media) -> Self {
Self {
audio,
id: None,
sample_rate: None,
timestamps: None,
model: None,
}
}
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn with_sample_rate(mut self, sample_rate: u32) -> Self {
self.sample_rate = Some(sample_rate);
self
}
pub fn with_timestamps(mut self, timestamps: Vec<WordTimestamp>) -> Self {
self.timestamps = Some(timestamps);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct WordTimestamp {
pub text: String,
pub start: f64,
pub end: f64,
}
impl WordTimestamp {
pub fn new(text: impl Into<String>, start: f64, end: f64) -> Self {
Self {
text: text.into(),
start,
end,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct VoiceInfo {
pub id: VoiceId,
pub name: String,
pub description: Option<String>,
pub language: Option<String>,
pub origin: VoiceOrigin,
#[serde(skip)]
pub preview: Option<Media>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum VoiceOrigin {
Preset,
Account,
Store,
}
impl VoiceInfo {
pub fn new(id: impl Into<String>, name: impl Into<String>, origin: VoiceOrigin) -> Self {
Self {
id: id.into(),
name: name.into(),
description: None,
language: None,
origin,
preview: None,
}
}
pub fn with_language(mut self, language: impl Into<String>) -> Self {
self.language = Some(language.into());
self
}
pub fn with_preview(mut self, preview: Media) -> Self {
self.preview = Some(preview);
self
}
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AudioModel {
pub id: String,
pub name: String,
pub description: Option<String>,
pub speech: bool,
pub dialogue: bool,
pub voice_design: bool,
}
impl AudioModel {
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
Self {
id: id.into(),
name: name.into(),
description: None,
speech: true,
dialogue: false,
voice_design: false,
}
}
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn with_speech(mut self, speech: bool) -> Self {
self.speech = speech;
self
}
pub fn with_dialogue(mut self, dialogue: bool) -> Self {
self.dialogue = dialogue;
self
}
pub fn with_voice_design(mut self, voice_design: bool) -> Self {
self.voice_design = voice_design;
self
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AudioError {
#[error(transparent)]
Http(HttpError),
#[error("audio API error (status {status}): {message}")]
Api { status: u16, message: String },
#[error("invalid audio API response: {0}")]
InvalidResponse(String),
#[error("not supported by the audio provider: {0}")]
Unsupported(&'static str),
#[error("no audio provider named '{0}'")]
UnknownProvider(String),
#[error("the API key is missing, set {0}")]
MissingApiKey(&'static str),
#[error("cannot save the audio: {0}")]
Storage(#[from] StorageError),
#[error("no voice: the provider needs one")]
MissingVoice,
#[error("no model for {0}")]
MissingModel(&'static str),
#[error("invalid audio request: {0}")]
InvalidRequest(String),
}
impl From<HttpError> for AudioError {
fn from(err: HttpError) -> Self {
match err {
HttpError::Status { status, message } => Self::Api { status, message },
err => Self::Http(err),
}
}
}
fn audio_media(response: &HttpResponse, content_type: &str) -> Result<Media, AudioError> {
if response.body.is_empty() {
return Err(AudioError::InvalidResponse(
"the response has no audio".to_string(),
));
}
Ok(Media::from_bytes(content_type, &response.body))
}
impl AudioError {
pub fn is_auth(&self) -> bool {
matches!(
self,
Self::Api {
status: 401 | 403,
..
}
)
}
}
#[async_trait]
pub trait SpeechProvider: Send + Sync + 'static {
async fn generate(&self, request: &SpeechRequest<'_>) -> Result<SpeechResponse, AudioError>;
fn supports_voice_cloning(&self) -> bool {
false
}
async fn create_voice(
&self,
name: &str,
source: VoiceSource,
description: Option<&str>,
) -> Result<VoiceId, AudioError> {
let _ = (name, source, description);
Err(AudioError::Unsupported("voice cloning"))
}
fn supports_dialogue(&self) -> bool {
false
}
async fn generate_dialogue(
&self,
request: &DialogueRequest<'_>,
) -> Result<SpeechResponse, AudioError> {
let _ = request;
Err(AudioError::Unsupported("dialogue"))
}
fn supports_voice_design(&self) -> bool {
false
}
async fn design_voice(
&self,
request: &DesignVoiceRequest<'_>,
) -> Result<Vec<VoicePreview>, AudioError> {
let _ = request;
Err(AudioError::Unsupported("voice design"))
}
async fn list_voices(&self) -> Result<Vec<VoiceInfo>, AudioError> {
Err(AudioError::Unsupported("listing voices"))
}
async fn list_models(&self) -> Result<Vec<AudioModel>, AudioError> {
Err(AudioError::Unsupported("listing models"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_preview_with_sample_id_is_a_sample_id() {
let preview = VoicePreview::new(Media::from_bytes("audio/mpeg", b"A"))
.with_sample_id("g1")
.with_text("Hi");
assert_eq!(
VoiceSource::from(&preview),
VoiceSource::SampleId("g1".into())
);
}
#[test]
fn a_preview_without_sample_id_is_samples() {
let audio = Media::from_bytes("audio/wav", b"A");
let preview = VoicePreview::new(audio.clone())
.with_text("Hi")
.with_language("pl");
assert_eq!(
VoiceSource::from(preview),
VoiceSource::samples(vec![audio], Some("Hi")).with_language("pl")
);
}
#[tokio::test]
async fn simple_providers_reject_timestamps() {
use agentai_core::mock::MockHttp;
use std::sync::Arc;
let http = MockHttp::new(vec![]);
let providers: Vec<Arc<dyn SpeechProvider>> = vec![
Arc::new(
openai::OpenAiSpeechProvider::new("tts-1", "k", "http://x")
.with_client(Arc::new(http.clone())),
),
Arc::new(
elevenlabs::ElevenLabsProvider::new("m", "k", "http://x")
.with_client(Arc::new(http.clone())),
),
Arc::new(
omlx::OmlxProvider::new("m", "", "http://x").with_client(Arc::new(http.clone())),
),
];
for provider in providers {
let err = crate::SpeechGenerator::new(provider)
.generate("hi")
.with_voice("a")
.with_timestamps(true)
.await
.unwrap_err();
assert!(matches!(err, AudioError::Unsupported(_)), "{err}");
}
assert_eq!(http.request_count(), 0);
}
}