pub mod elevenlabs;
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::Serialize;
use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Voice {
Id(String),
Description(String),
Auto(String),
}
impl Voice {
pub fn id(id: impl Into<String>) -> Self {
Self::Id(id.into())
}
pub fn description(description: impl Into<String>) -> Self {
Self::Description(description.into())
}
pub fn auto(value: impl Into<String>) -> Self {
Self::Auto(value.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",
}
}
}
pub(crate) fn extension_for(content_type: &str) -> &str {
let content_type = content_type.split(';').next().unwrap_or("").trim();
match content_type {
"audio/mpeg" => "mp3",
"audio/wav" => "wav",
"audio/ogg" => "opus",
"audio/flac" => "flac",
"audio/aac" => "aac",
"audio/pcm" => "pcm",
other => other.rsplit('/').next().unwrap_or(other),
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SpeechRequest {
pub text: String,
pub voice: Option<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>,
}
impl SpeechRequest {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
voice: None,
default_voice: None,
format: None,
speed: None,
language: None,
instructions: None,
name: None,
}
}
pub fn with_voice(mut self, voice: Voice) -> Self {
self.voice = Some(voice);
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
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SpeechResponse {
pub audio: Media,
pub id: Option<String>,
pub sample_rate: Option<u32>,
}
impl SpeechResponse {
pub fn new(audio: Media) -> Self {
Self {
audio,
id: None,
sample_rate: 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
}
}
#[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,
samples: &[Media],
transcript: Option<&str>,
description: Option<&str>,
) -> Result<String, AudioError> {
let _ = (name, samples, transcript, description);
Err(AudioError::Unsupported("voice cloning"))
}
fn supports_voice_description(&self) -> bool {
false
}
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,
Omlx,
}
impl ProviderKind {
fn from_name(name: &str) -> Option<Self> {
match name {
"openai" => Some(Self::OpenAi),
"elevenlabs" => Some(Self::ElevenLabs),
"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::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)]
pub(crate) mod test_support {
use agentai_core::{HttpClient, HttpError, HttpRequest, HttpResponse};
use async_trait::async_trait;
use serde_json::Value;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
#[derive(Default)]
pub(crate) struct MockHttp {
pub(crate) requests: Mutex<Vec<HttpRequest>>,
responses: Mutex<VecDeque<HttpResponse>>,
}
impl MockHttp {
pub(crate) fn new(responses: Vec<HttpResponse>) -> Arc<Self> {
Arc::new(Self {
requests: Mutex::default(),
responses: Mutex::new(responses.into()),
})
}
pub(crate) fn request(&self, index: usize) -> HttpRequest {
self.requests.lock().unwrap()[index].clone()
}
}
#[async_trait]
impl HttpClient for MockHttp {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpError> {
self.requests.lock().unwrap().push(request);
Ok(self
.responses
.lock()
.unwrap()
.pop_front()
.expect("no response left"))
}
}
pub(crate) fn json_response(status: u16, body: Value) -> HttpResponse {
HttpResponse::new(status, body.to_string())
}
pub(crate) fn body_json(request: &HttpRequest) -> Value {
serde_json::from_slice(request.body.as_ref().unwrap()).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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("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(_))
));
}
#[test]
fn extension_ignores_mime_parameters() {
assert_eq!(extension_for("audio/webm;codecs=opus"), "webm");
assert_eq!(extension_for("audio/mpeg; charset=x"), "mp3");
}
}