agentai-audio 0.6.0

Text-to-speech and voice cloning for AgentAI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! # oMLX speech API
//!
//! [`OmlxProvider`] speaks text with `POST /audio/speech` of an oMLX
//! server, for example with `mlx-community/VoxCPM2-8bit`. The server has no voice list: a voice
//! is a text description (sent as `instructions`) or a cloned voice. oMLX clones from a sample
//! sent with every request (`ref_audio` and `ref_text`), so the provider keeps the samples in a
//! [`VoiceStore`] set with [`with_voice_store`](OmlxProvider::with_voice_store).
//!
//! Every field of a request has an equivalent, so none is left out. What the server does not
//! accept comes back as [`AudioError::Api`].

use super::{
    AudioError, AudioFormat, SpeechProvider, SpeechRequest, SpeechResponse, Voice, VoiceInfo,
    audio_media,
};
use crate::voice_store::{StoredVoice, VoiceStore};
use agentai_core::message::{Media, MediaSource};
use agentai_core::{HttpClient, HttpError, HttpRequest, ReqwestClient};
use async_trait::async_trait;
use serde::Serialize;
use std::sync::Arc;

/// The default endpoint of a local oMLX server.
pub const DEFAULT_BASE_URL: &str = "http://localhost:8000/v1";
/// Environment variable with the endpoint.
pub const ENDPOINT_ENV: &str = "OMLX_ENDPOINT";
/// Environment variable with the API key. It is optional.
pub const API_KEY_ENV: &str = "OMLX_API_KEY";

/// Provider for the speech API of an oMLX server.
///
/// ```rust,no_run
/// # use agentai_audio::provider::omlx::OmlxProvider;
/// # use agentai_audio::MemoryVoiceStore;
/// # fn main() -> Result<(), agentai_audio::AudioError> {
/// let provider = OmlxProvider::from_env("mlx-community/VoxCPM2-8bit")?
///     .with_voice_store(MemoryVoiceStore::new());
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct OmlxProvider {
    model: String,
    api_key: String,
    base_url: String,
    client: Arc<dyn HttpClient>,
    store: Option<Arc<dyn VoiceStore>>,
}

impl std::fmt::Debug for OmlxProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OmlxProvider")
            .field("model", &self.model)
            .field("base_url", &self.base_url)
            .finish_non_exhaustive()
    }
}

impl OmlxProvider {
    /// Creates a provider for `model` with the API key and base URL given in code, for example
    /// [`DEFAULT_BASE_URL`]. An empty key sends no `Authorization` header.
    pub fn new(
        model: impl Into<String>,
        api_key: impl Into<String>,
        base_url: impl Into<String>,
    ) -> Self {
        Self {
            model: model.into(),
            api_key: api_key.into(),
            base_url: base_url.into().trim_end_matches('/').to_string(),
            client: Arc::new(ReqwestClient::new()),
            store: None,
        }
    }

    /// Creates a provider for `model` with the endpoint from `OMLX_ENDPOINT`, or
    /// [`DEFAULT_BASE_URL`] when it is not set, and the optional API key from `OMLX_API_KEY`.
    ///
    /// No voice store is created, so cloning needs [`with_voice_store`](Self::with_voice_store).
    pub fn from_env(model: impl Into<String>) -> Result<Self, AudioError> {
        Ok(Self::from_lookup(model, |name| std::env::var(name).ok()))
    }

    fn from_lookup(model: impl Into<String>, lookup: impl Fn(&str) -> Option<String>) -> Self {
        Self::new(
            model,
            lookup(API_KEY_ENV).unwrap_or_default(),
            lookup(ENDPOINT_ENV).unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
        )
    }

    /// Sets the store of cloned voices. It enables
    /// [`create_voice`](SpeechProvider::create_voice) and [`Voice::Id`].
    pub fn with_voice_store(mut self, store: impl VoiceStore) -> Self {
        self.store = Some(Arc::new(store));
        self
    }

    #[cfg(test)]
    pub(crate) fn with_client(mut self, client: Arc<dyn HttpClient>) -> Self {
        self.client = client;
        self
    }

    /// The cloned voice and the instructions of a request.
    async fn resolve(
        &self,
        request: &SpeechRequest,
    ) -> Result<(Option<StoredVoice>, Option<String>), AudioError> {
        let mut description = None;
        let mut cloned = None;
        match request.voice.as_ref().or(request.default_voice.as_ref()) {
            None => {}
            Some(Voice::Description(text)) => description = Some(text.clone()),
            Some(Voice::Id(id)) => {
                let store = self
                    .store
                    .as_ref()
                    .ok_or(AudioError::Unsupported("voice IDs without a voice store"))?;
                cloned = Some(store.get(id).await?.ok_or_else(|| {
                    AudioError::InvalidRequest(format!("no cloned voice with id '{id}'"))
                })?);
            }
            Some(Voice::Auto(text)) => {
                if let Some(store) = &self.store {
                    cloned = store.get(text).await?;
                }
                if cloned.is_none() {
                    description = Some(text.clone());
                }
            }
        }
        let instructions = match (description, &request.instructions) {
            (Some(description), Some(extra)) => Some(format!("{description}\n{extra}")),
            (Some(description), None) => Some(description),
            (None, extra) => extra.clone(),
        };
        Ok((cloned, instructions))
    }
}

#[derive(Serialize)]
struct SpeechBody<'a> {
    model: &'a str,
    input: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    response_format: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    speed: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    language: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    instructions: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ref_audio: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ref_text: Option<&'a str>,
}

fn format_name(format: AudioFormat) -> &'static str {
    match format {
        AudioFormat::Mp3 => "mp3",
        AudioFormat::Wav => "wav",
        AudioFormat::Opus => "opus",
        AudioFormat::Flac => "flac",
        AudioFormat::Aac => "aac",
        AudioFormat::Pcm => "pcm",
    }
}

#[async_trait]
impl SpeechProvider for OmlxProvider {
    fn model(&self) -> Option<&str> {
        Some(&self.model)
    }

    async fn generate(&self, request: SpeechRequest) -> Result<SpeechResponse, AudioError> {
        let response_format = request.format.map(format_name);
        let (cloned, instructions) = self.resolve(&request).await?;
        let ref_audio = match cloned.as_ref().map(|voice| &voice.sample.source) {
            Some(MediaSource::Base64(data)) => Some(data.as_str()),
            // `create_voice` stores base64, but a custom store may hold anything
            Some(MediaSource::Url(_)) => {
                return Err(AudioError::InvalidRequest(
                    "the stored voice sample is not base64".to_string(),
                ));
            }
            None => None,
        };
        let ref_text = cloned
            .as_ref()
            .and_then(|voice| voice.transcript.as_deref());
        let body = SpeechBody {
            model: &self.model,
            input: &request.text,
            response_format,
            speed: request.speed,
            language: request.language.as_deref(),
            instructions,
            ref_audio,
            ref_text,
        };
        let http = HttpRequest::post(format!("{}/audio/speech", self.base_url))
            .with_json(&body)?
            .with_bearer_token(&self.api_key);
        let response = self.client.send(http).await?.error_for_status()?;
        let format = request.format.unwrap_or(AudioFormat::Wav);
        let mut audio = audio_media(&response, format.content_type())?;
        audio.name = request.name;
        Ok(SpeechResponse::new(audio))
    }

    fn supports_voice_cloning(&self) -> bool {
        self.store.is_some()
    }

    /// Stores the sample in the voice store; nothing is sent to the server until a request
    /// uses the voice. Needs exactly one sample. Without `transcript` the server answers such a
    /// request with an error, which is returned as [`AudioError::Api`].
    async fn create_voice(
        &self,
        name: &str,
        samples: &[Media],
        transcript: Option<&str>,
        description: Option<&str>,
    ) -> Result<String, AudioError> {
        let store = self.store.as_ref().ok_or(AudioError::Unsupported(
            "voice cloning without a voice store",
        ))?;
        let [sample] = samples else {
            return Err(AudioError::InvalidRequest(format!(
                "oMLX clones from exactly one sample, got {}",
                samples.len()
            )));
        };
        // Decoding also rejects what oMLX would, for example a `data:` URL
        let bytes = sample.bytes(&*self.client).await.map_err(|err| match err {
            HttpError::InvalidMedia(message) => AudioError::InvalidRequest(message),
            err => err.into(),
        })?;
        let mut stored = Media::from_bytes(sample.content_type.as_str(), bytes);
        stored.name = sample.name.clone();
        let mut voice = StoredVoice::new(name, stored);
        voice.description = description.map(str::to_string);
        voice.transcript = transcript.map(str::to_string);
        Ok(store.save(voice).await?)
    }

    fn supports_voice_description(&self) -> bool {
        true
    }

    /// The cloned voices of the voice store.
    async fn list_voices(&self) -> Result<Vec<VoiceInfo>, AudioError> {
        let store = self.store.as_ref().ok_or(AudioError::Unsupported(
            "listing voices without a voice store",
        ))?;
        Ok(store
            .list()
            .await?
            .into_iter()
            .map(|(id, voice)| {
                let mut info = VoiceInfo::new(id, voice.name).with_cloned(true);
                info.description = voice.description;
                info
            })
            .collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::provider::test_support::{MockHttp, body_json};
    use crate::provider::{AudioError, SpeechProvider, SpeechRequest, Voice, VoiceInfo};
    use crate::{MemoryVoiceStore, VoiceStore};
    use agentai_core::HttpResponse;
    use agentai_core::message::{Media, MediaSource};
    use serde_json::json;
    use std::sync::Arc;

    fn audio() -> HttpResponse {
        HttpResponse::new(200, b"audio".to_vec())
    }

    fn provider(http: &Arc<MockHttp>) -> OmlxProvider {
        OmlxProvider::new("m", "", "http://local/v1").with_client(http.clone())
    }

    fn sample() -> Media {
        Media::from_bytes("audio/wav", b"WAV")
    }

    async fn cloned(http: &Arc<MockHttp>, transcript: Option<&str>) -> OmlxProvider {
        let p = provider(http).with_voice_store(MemoryVoiceStore::new());
        let id = p
            .create_voice("Adam", &[sample()], transcript, None)
            .await
            .unwrap();
        assert_eq!(id, "voice-1");
        p
    }

    #[tokio::test]
    async fn generate_without_a_voice_sends_no_voice_field() {
        let http = MockHttp::new(vec![audio()]);
        let r = provider(&http)
            .generate(SpeechRequest::new("hi"))
            .await
            .unwrap();
        assert_eq!(http.request(0).url, "http://local/v1/audio/speech");
        assert_eq!(
            body_json(&http.request(0)),
            json!({"model": "m", "input": "hi"})
        );
        assert_eq!(r.audio.content_type, "audio/wav");
        assert_eq!(r.sample_rate, None);
    }

    #[test]
    fn endpoint_keeps_v1() {
        let p = OmlxProvider::from_lookup("m", |name| {
            (name == ENDPOINT_ENV).then(|| "http://mini:8000/v1/".to_string())
        })
        .with_client(MockHttp::new(vec![audio()]));
        assert_eq!(p.base_url, "http://mini:8000/v1");
        assert_eq!(
            OmlxProvider::from_lookup("m", |_| None).base_url,
            DEFAULT_BASE_URL
        );
    }

    #[tokio::test]
    async fn create_voice_then_speak_with_it() {
        let http = MockHttp::new(vec![audio()]);
        let store = MemoryVoiceStore::new();
        let p = provider(&http).with_voice_store(store.clone());
        assert!(p.supports_voice_cloning());
        let id = p
            .create_voice("Adam", &[sample()], Some("hello"), None)
            .await
            .unwrap();
        assert_eq!(id, "voice-1");
        assert!(http.requests.lock().unwrap().is_empty());
        p.generate(SpeechRequest::new("hi").with_voice(Voice::id(&id)))
            .await
            .unwrap();
        let body = body_json(&http.request(0));
        assert_eq!(body["ref_audio"], json!("V0FW"));
        assert_eq!(body["ref_text"], json!("hello"));
        assert!(body.get("voice").is_none());
    }

    #[tokio::test]
    async fn a_missing_transcript_sends_no_ref_text() {
        let http = MockHttp::new(vec![audio()]);
        let p = cloned(&http, None).await;
        p.generate(SpeechRequest::new("hi").with_voice(Voice::id("voice-1")))
            .await
            .unwrap();
        let body = body_json(&http.request(0));
        assert_eq!(body["ref_audio"], json!("V0FW"));
        assert!(body.get("ref_text").is_none());
    }

    #[tokio::test]
    async fn auto_is_a_clone_only_when_stored() {
        let http = MockHttp::new(vec![audio(), audio()]);
        let p = cloned(&http, Some("hello")).await;
        p.generate(SpeechRequest::new("hi").with_voice(Voice::auto("voice-1")))
            .await
            .unwrap();
        let body = body_json(&http.request(0));
        assert_eq!(body["ref_audio"], json!("V0FW"));
        assert!(body.get("instructions").is_none());
        p.generate(SpeechRequest::new("hi").with_voice(Voice::auto("deep male voice")))
            .await
            .unwrap();
        let body = body_json(&http.request(1));
        assert_eq!(body["instructions"], json!("deep male voice"));
        assert!(body.get("ref_audio").is_none());
    }

    #[tokio::test]
    async fn description_joins_instructions() {
        let http = MockHttp::new(vec![audio()]);
        provider(&http)
            .generate(
                SpeechRequest::new("hi")
                    .with_voice(Voice::description("warm"))
                    .with_instructions("slowly"),
            )
            .await
            .unwrap();
        assert_eq!(
            body_json(&http.request(0))["instructions"],
            json!("warm\nslowly")
        );
    }

    #[tokio::test]
    async fn the_default_voice_resolves_like_a_voice() {
        let http = MockHttp::new(vec![audio()]);
        let p = cloned(&http, Some("hello")).await;
        p.generate(SpeechRequest::new("hi").with_default_voice(Voice::id("voice-1")))
            .await
            .unwrap();
        assert_eq!(body_json(&http.request(0))["ref_audio"], json!("V0FW"));
    }

    #[tokio::test]
    async fn without_a_store() {
        let http = MockHttp::new(vec![audio()]);
        let p = provider(&http);
        assert!(!p.supports_voice_cloning());
        assert!(matches!(
            p.create_voice("A", &[sample()], None, None).await,
            Err(AudioError::Unsupported(_))
        ));
        assert!(matches!(
            p.generate(SpeechRequest::new("hi").with_voice(Voice::id("x")))
                .await,
            Err(AudioError::Unsupported(_))
        ));
        assert!(matches!(
            p.list_voices().await,
            Err(AudioError::Unsupported(_))
        ));
        assert!(http.requests.lock().unwrap().is_empty());
        p.generate(SpeechRequest::new("hi").with_voice(Voice::auto("x")))
            .await
            .unwrap();
        assert_eq!(body_json(&http.request(0))["instructions"], json!("x"));
    }

    #[tokio::test]
    async fn unknown_id_with_a_store() {
        let http = MockHttp::new(vec![]);
        let p = provider(&http).with_voice_store(MemoryVoiceStore::new());
        assert!(matches!(
            p.generate(SpeechRequest::new("hi").with_voice(Voice::id("nope")))
                .await,
            Err(AudioError::InvalidRequest(_))
        ));
        assert!(http.requests.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn exactly_one_sample() {
        let http = MockHttp::new(vec![]);
        let store = MemoryVoiceStore::new();
        let p = provider(&http).with_voice_store(store.clone());
        for samples in [vec![], vec![sample(), sample()]] {
            assert!(matches!(
                p.create_voice("A", &samples, None, None).await,
                Err(AudioError::InvalidRequest(_))
            ));
        }
        assert!(store.list().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn url_samples_are_downloaded_once() {
        let http = MockHttp::new(vec![HttpResponse::new(200, b"WAV".to_vec()), audio()]);
        let store = MemoryVoiceStore::new();
        let p = provider(&http).with_voice_store(store.clone());
        let url_sample = Media::from_url("audio/wav", "http://x/a.wav");
        let id = p
            .create_voice("A", &[url_sample], None, None)
            .await
            .unwrap();
        let stored = store.get(&id).await.unwrap().unwrap();
        assert_eq!(
            stored.sample.source,
            MediaSource::Base64("V0FW".to_string())
        );
        p.generate(SpeechRequest::new("hi").with_voice(Voice::id(&id)))
            .await
            .unwrap();
        let requests = http.requests.lock().unwrap();
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[0].url, "http://x/a.wav");
        assert_eq!(requests[1].url, "http://local/v1/audio/speech");
    }

    #[tokio::test]
    async fn failed_download_stores_nothing() {
        let http = MockHttp::new(vec![HttpResponse::new(404, b"gone".to_vec())]);
        let store = MemoryVoiceStore::new();
        let p = provider(&http).with_voice_store(store.clone());
        let url_sample = Media::from_url("audio/wav", "http://x/a.wav");
        let result = p.create_voice("A", &[url_sample], None, None).await;
        assert!(matches!(result, Err(AudioError::Api { status: 404, .. })));
        assert!(store.list().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn list_voices_reads_the_store() {
        let http = MockHttp::new(vec![]);
        let p = provider(&http).with_voice_store(MemoryVoiceStore::new());
        assert!(p.supports_voice_description());
        p.create_voice("Adam", &[sample()], None, Some("calm"))
            .await
            .unwrap();
        assert_eq!(
            p.list_voices().await.unwrap(),
            vec![
                VoiceInfo::new("voice-1", "Adam")
                    .with_description("calm")
                    .with_cloned(true)
            ]
        );
    }

    #[tokio::test]
    async fn create_voice_rejects_a_data_url_sample() {
        let p = provider(&MockHttp::new(vec![])).with_voice_store(MemoryVoiceStore::new());
        let sample = Media::from_base64("audio/wav", "data:audio/wav;base64,V0FW");
        let err = p
            .create_voice("A", &[sample], None, None)
            .await
            .unwrap_err();
        assert!(matches!(err, AudioError::InvalidRequest(_)));
    }
}