pub mod elevenlabs;
pub mod fishaudio;
pub mod omlx;
pub mod openai;
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;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Voice {
Id(String),
}
impl Voice {
pub fn id(id: impl Into<String>) -> Self {
Self::Id(id.into())
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum VoiceSource {
Samples {
samples: Vec<Media>,
transcript: 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),
}
}
}
#[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>,
}
impl VoicePreview {
pub fn new(audio: Media) -> Self {
Self {
audio,
text: None,
sample_id: None,
sample_rate: None,
}
}
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,
},
}
}
}
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 SpeechRequest {
pub text: String,
pub voices: Vec<Voice>,
pub default_voice: Option<Voice>,
pub format: Option<AudioFormat>,
pub speed: Option<f64>,
pub language: Option<String>,
pub instructions: Option<String>,
pub name: Option<String>,
pub timestamps: bool,
}
impl SpeechRequest {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
voices: Vec::new(),
default_voice: None,
format: None,
speed: None,
language: None,
instructions: None,
name: None,
timestamps: false,
}
}
pub fn with_voice(mut self, voice: Voice) -> Self {
self.voices.push(voice);
self
}
pub fn with_voices(mut self, voices: Vec<Voice>) -> Self {
self.voices = voices;
self
}
pub fn with_default_voice(mut self, voice: Voice) -> Self {
self.default_voice = Some(voice);
self
}
pub fn with_format(mut self, format: AudioFormat) -> Self {
self.format = Some(format);
self
}
pub fn with_speed(mut self, speed: f64) -> Self {
self.speed = Some(speed);
self
}
pub fn with_language(mut self, language: impl Into<String>) -> Self {
self.language = Some(language.into());
self
}
pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn with_timestamps(mut self, timestamps: bool) -> Self {
self.timestamps = timestamps;
self
}
pub(crate) fn without_timestamps(&self) -> Result<(), AudioError> {
if self.timestamps {
Err(AudioError::Unsupported("word timestamps"))
} else {
Ok(())
}
}
pub(crate) fn request_voice(&self) -> Result<Option<&Voice>, AudioError> {
match self.voices.as_slice() {
[] => Ok(None),
[voice] => Ok(Some(voice)),
_ => Err(AudioError::Unsupported("more than one voice")),
}
}
pub(crate) fn single_voice(&self) -> Result<Option<&Voice>, AudioError> {
Ok(self.request_voice()?.or(self.default_voice.as_ref()))
}
}
#[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>>,
}
impl SpeechResponse {
pub fn new(audio: Media) -> Self {
Self {
audio,
id: None,
sample_rate: None,
timestamps: None,
}
}
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: String,
pub name: String,
pub description: Option<String>,
pub cloned: bool,
}
impl VoiceInfo {
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
Self {
id: id.into(),
name: name.into(),
description: None,
cloned: false,
}
}
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn with_cloned(mut self, cloned: bool) -> Self {
self.cloned = cloned;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AudioModel {
pub model: String,
pub id: String,
pub name: Option<String>,
pub description: Option<String>,
}
impl AudioModel {
pub fn new(model: impl Into<String>, id: impl Into<String>) -> Self {
Self {
model: model.into(),
id: id.into(),
name: None,
description: None,
}
}
}
#[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 for model '{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: set a voice or a default voice")]
MissingVoice,
#[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 {
fn model(&self) -> Option<&str> {
None
}
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<String, AudioError> {
let _ = (name, source, description);
Err(AudioError::Unsupported("voice cloning"))
}
fn supports_voice_design(&self) -> bool {
false
}
async fn design_voice(
&self,
description: &str,
text: Option<&str>,
count: usize,
) -> Result<Vec<VoicePreview>, AudioError> {
let _ = (description, text, count);
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"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProviderKind {
OpenAi,
ElevenLabs,
FishAudio,
Omlx,
}
impl ProviderKind {
fn from_name(name: &str) -> Option<Self> {
match name {
"openai" => Some(Self::OpenAi),
"elevenlabs" => Some(Self::ElevenLabs),
"fishaudio" => Some(Self::FishAudio),
"omlx" => Some(Self::Omlx),
_ => None,
}
}
fn build(self, model: &str) -> Result<Box<dyn SpeechProvider>, AudioError> {
Ok(match self {
Self::OpenAi => Box::new(openai::OpenAiSpeechProvider::from_env(model)?),
Self::ElevenLabs => Box::new(elevenlabs::ElevenLabsProvider::from_env(model)?),
Self::FishAudio => Box::new(fishaudio::FishAudioProvider::from_env(model)?),
Self::Omlx => Box::new(omlx::OmlxProvider::from_env(model)?),
})
}
}
fn resolve(model: &str) -> Result<(ProviderKind, &str), AudioError> {
let unknown = || AudioError::UnknownProvider(model.to_string());
match model.split_once("::") {
Some((provider, name)) => ProviderKind::from_name(provider)
.map(|kind| (kind, name))
.ok_or_else(unknown),
None if model.starts_with("tts-1") || model.starts_with("gpt-4o-mini-tts") => {
Ok((ProviderKind::OpenAi, model))
}
None if model.starts_with("eleven_") => Ok((ProviderKind::ElevenLabs, model)),
None => Err(unknown()),
}
}
pub fn from_model(model: &str) -> Result<Box<dyn SpeechProvider>, AudioError> {
let (kind, name) = resolve(model)?;
kind.build(name)
}
pub async fn list_models(provider: &str) -> Result<Vec<AudioModel>, AudioError> {
let kind = ProviderKind::from_name(provider)
.ok_or_else(|| AudioError::UnknownProvider(provider.to_string()))?;
kind.build("")?.list_models().await
}
#[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");
assert_eq!(
VoiceSource::from(preview),
VoiceSource::Samples {
samples: vec![audio],
transcript: Some("Hi".into())
}
);
}
#[test]
fn model_names_select_the_provider() {
assert_eq!(
resolve("omlx::mlx-community/VoxCPM2-8bit").unwrap(),
(ProviderKind::Omlx, "mlx-community/VoxCPM2-8bit")
);
assert_eq!(
resolve("elevenlabs::x").unwrap(),
(ProviderKind::ElevenLabs, "x")
);
assert_eq!(
resolve("fishaudio::drama-3").unwrap(),
(ProviderKind::FishAudio, "drama-3")
);
assert_eq!(
resolve("eleven_v4").unwrap(),
(ProviderKind::ElevenLabs, "eleven_v4")
);
assert_eq!(
resolve("tts-1-hd").unwrap(),
(ProviderKind::OpenAi, "tts-1-hd")
);
assert_eq!(
resolve("gpt-4o-mini-tts").unwrap(),
(ProviderKind::OpenAi, "gpt-4o-mini-tts")
);
assert!(matches!(
resolve("gpt-4o"),
Err(AudioError::UnknownProvider(_))
));
assert!(matches!(
resolve("nope::x"),
Err(AudioError::UnknownProvider(_))
));
}
#[tokio::test]
async fn simple_providers_reject_several_voices_and_timestamps() {
use agentai_core::mock::MockHttp;
use std::sync::Arc;
let http = MockHttp::new(vec![]);
let providers: Vec<Box<dyn SpeechProvider>> = vec![
Box::new(
openai::OpenAiSpeechProvider::new("tts-1", "k", "http://x")
.with_client(Arc::new(http.clone())),
),
Box::new(
elevenlabs::ElevenLabsProvider::new("m", "k", "http://x")
.with_client(Arc::new(http.clone())),
),
Box::new(
omlx::OmlxProvider::new("m", "", "http://x").with_client(Arc::new(http.clone())),
),
];
let several = SpeechRequest::new("hi")
.with_voice(Voice::id("a"))
.with_voice(Voice::id("b"));
let timestamps = SpeechRequest::new("hi")
.with_voice(Voice::id("a"))
.with_timestamps(true);
for provider in providers {
for request in [several.clone(), timestamps.clone()] {
let err = provider.generate(request).await.unwrap_err();
assert!(matches!(err, AudioError::Unsupported(_)), "{err}");
}
}
assert_eq!(http.request_count(), 0);
}
}