agentai-audio 0.7.1

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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! # ElevenLabs speech API
//!
//! [`ElevenLabsProvider`] speaks text with `POST /v1/text-to-speech/{voice_id}`, clones voices
//! with `POST /v1/voices/add` and lists voices and models. It designs voices from a description
//! with `POST /v1/text-to-voice/design` and saves a chosen preview with `POST /v1/text-to-voice`.
//!
//! Fields without an equivalent are not sent: `instructions` is ignored.

use super::{
    AudioError, AudioFormat, AudioModel, SpeechProvider, SpeechRequest, SpeechResponse, Voice,
    VoiceInfo, VoicePreview, VoiceSource, audio_media,
};
use agentai_core::message::Media;
use agentai_core::{HttpClient, HttpRequest, Multipart, ReqwestClient, percent_encode};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// The ElevenLabs API endpoint.
pub const DEFAULT_BASE_URL: &str = "https://api.elevenlabs.io";
/// Environment variable with the API key.
pub const API_KEY_ENV: &str = "ELEVENLABS_API_KEY";
/// Environment variable with the base URL.
pub const BASE_URL_ENV: &str = "ELEVENLABS_BASE_URL";

/// Provider for the ElevenLabs API.
///
/// ```rust,no_run
/// # use agentai_audio::provider::elevenlabs::ElevenLabsProvider;
/// # fn main() -> Result<(), agentai_audio::AudioError> {
/// // From `ELEVENLABS_API_KEY`
/// let provider = ElevenLabsProvider::from_env("eleven_multilingual_v2")?;
/// // Or everything in code
/// let provider = ElevenLabsProvider::new(
///     "eleven_multilingual_v2",
///     "xi-...",
///     "https://api.elevenlabs.io",
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct ElevenLabsProvider {
    model: String,
    api_key: String,
    base_url: String,
    output_format: Option<String>,
    client: Arc<dyn HttpClient>,
}

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

impl ElevenLabsProvider {
    /// Creates a provider for `model` with the API key and base URL given in code, for example
    /// [`DEFAULT_BASE_URL`].
    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(),
            output_format: None,
            client: Arc::new(ReqwestClient::new()),
        }
    }

    /// Creates a provider for `model` with the API key from `ELEVENLABS_API_KEY` and the base
    /// URL from `ELEVENLABS_BASE_URL`, or [`DEFAULT_BASE_URL`] when it is not set.
    pub fn from_env(model: impl Into<String>) -> Result<Self, AudioError> {
        Self::from_lookup(model, |name| std::env::var(name).ok())
    }

    fn from_lookup(
        model: impl Into<String>,
        lookup: impl Fn(&str) -> Option<String>,
    ) -> Result<Self, AudioError> {
        let api_key = lookup(API_KEY_ENV).ok_or(AudioError::MissingApiKey(API_KEY_ENV))?;
        let base_url = lookup(BASE_URL_ENV).unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
        Ok(Self::new(model, api_key, base_url))
    }

    /// Sets the `output_format` of the API, for example `pcm_16000`. It wins over the format of
    /// the request.
    pub fn with_output_format(mut self, output_format: impl Into<String>) -> Self {
        self.output_format = Some(output_format.into());
        self
    }

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

    fn get(&self, path: &str) -> HttpRequest {
        self.authorize(HttpRequest::get(format!("{}{path}", self.base_url)))
    }

    fn authorize(&self, request: HttpRequest) -> HttpRequest {
        request.with_header("xi-api-key", self.api_key.as_str())
    }

    /// The path segment of the voice: the request voice, else the default voice.
    fn voice_id<'a>(&self, request: &'a SpeechRequest) -> Result<&'a str, AudioError> {
        let voice = request.single_voice()?.ok_or(AudioError::MissingVoice)?;
        let Voice::Id(id) = voice;
        let safe = !id.is_empty()
            && id
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
        if safe {
            Ok(id)
        } else {
            Err(AudioError::InvalidRequest(format!(
                "invalid ElevenLabs voice ID '{id}'"
            )))
        }
    }
}

/// The `output_format` for a format of the request.
fn output_format_for(format: AudioFormat) -> Result<&'static str, AudioError> {
    match format {
        AudioFormat::Pcm => Ok("pcm_24000"),
        AudioFormat::Mp3 => Ok("mp3_44100_128"),
        AudioFormat::Wav => Ok("wav_44100"),
        AudioFormat::Opus => Ok("opus_48000_128"),
        AudioFormat::Flac => Err(AudioError::Unsupported("FLAC output with ElevenLabs")),
        AudioFormat::Aac => Err(AudioError::Unsupported("AAC output with ElevenLabs")),
    }
}

/// MIME type of an `output_format` such as `mp3_44100_128`.
fn content_type_of(output_format: &str) -> &'static str {
    match output_format.split('_').next().unwrap_or_default() {
        "mp3" => "audio/mpeg",
        "pcm" => "audio/pcm",
        "wav" => "audio/wav",
        "opus" => "audio/ogg",
        "ulaw" => "audio/basic",
        "alaw" => "audio/x-alaw-basic",
        _ => "application/octet-stream",
    }
}

/// The sample rate of a `pcm_<rate>` output format.
fn pcm_sample_rate(output_format: &str) -> Option<u32> {
    output_format.strip_prefix("pcm_")?.parse().ok()
}

#[derive(Serialize)]
struct SpeechBody<'a> {
    text: &'a str,
    model_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    language_code: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    voice_settings: Option<VoiceSettings>,
}

#[derive(Serialize)]
struct VoiceSettings {
    speed: f64,
}

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

    async fn generate(&self, request: SpeechRequest) -> Result<SpeechResponse, AudioError> {
        request.without_timestamps()?;
        let voice = self.voice_id(&request)?;
        let output_format = match (&self.output_format, request.format) {
            (Some(over), _) => Some(over.as_str()),
            (None, Some(format)) => Some(output_format_for(format)?),
            (None, None) => None,
        };
        let mut url = format!("{}/v1/text-to-speech/{voice}", self.base_url);
        if let Some(output_format) = output_format {
            url.push_str("?output_format=");
            url.push_str(&percent_encode(output_format));
        }
        let body = SpeechBody {
            text: &request.text,
            model_id: &self.model,
            language_code: request.language.as_deref(),
            voice_settings: request.speed.map(|speed| VoiceSettings { speed }),
        };
        let http = self.authorize(HttpRequest::post(url).with_json(&body)?);
        let response = self.client.send(http).await?.error_for_status()?;
        let content_type = output_format.map_or("audio/mpeg", content_type_of);
        let mut audio = audio_media(&response, content_type)?;
        audio.name = request.name;
        let mut result = SpeechResponse::new(audio);
        if let Some(rate) = output_format.and_then(pcm_sample_rate) {
            result = result.with_sample_rate(rate);
        }
        Ok(result)
    }

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

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

    /// Designs voices with `POST /v1/text-to-voice/design`. The API picks the number of
    /// previews, so `count` is not used. Without `text` the API writes one itself. Keep a
    /// preview by passing its `sample_id` to `create_voice`.
    async fn design_voice(
        &self,
        description: &str,
        text: Option<&str>,
        _count: usize,
    ) -> Result<Vec<VoicePreview>, AudioError> {
        let body = DesignBody {
            voice_description: description,
            text,
            auto_generate_text: text.is_none().then_some(true),
        };
        let http = self
            .authorize(HttpRequest::post(format!(
                "{}/v1/text-to-voice/design",
                self.base_url
            )))
            .with_json(&body)?;
        let response = self.client.send(http).await?.error_for_status()?;
        let designed: DesignResponse = response
            .json()
            .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
        designed
            .previews
            .into_iter()
            .map(|preview| {
                let bytes = agentai_core::base64::decode(&preview.audio_base_64)
                    .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
                let audio = Media::from_bytes(preview.media_type, &bytes);
                let result = VoicePreview::new(audio).with_sample_id(preview.generated_voice_id);
                Ok(match designed.text.as_deref().or(text) {
                    Some(text) => result.with_text(text),
                    None => result,
                })
            })
            .collect()
    }

    /// Clones a voice from the samples with `POST /v1/voices/add` and returns its ID. A
    /// [`VoiceSource::SampleId`] saves a designed preview with `POST /v1/text-to-voice`; the
    /// API requires a `description` for it.
    ///
    /// When the API replies with `requires_verification: true`, the voice exists but cannot
    /// speak until it is verified at ElevenLabs. `transcript` is not used.
    async fn create_voice(
        &self,
        name: &str,
        source: VoiceSource,
        description: Option<&str>,
    ) -> Result<String, AudioError> {
        let samples = match source {
            VoiceSource::Samples { samples, .. } => samples,
            VoiceSource::SampleId(generated_voice_id) => {
                let body = SaveVoiceBody {
                    voice_name: name,
                    voice_description: description,
                    generated_voice_id: &generated_voice_id,
                };
                let http = self
                    .authorize(HttpRequest::post(format!(
                        "{}/v1/text-to-voice",
                        self.base_url
                    )))
                    .with_json(&body)?;
                let response = self.client.send(http).await?.error_for_status()?;
                let created: CreatedVoice = response
                    .json()
                    .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
                return Ok(created.voice_id);
            }
        };
        if samples.is_empty() {
            return Err(AudioError::InvalidRequest(
                "voice cloning needs at least one sample".to_string(),
            ));
        }
        let mut form = Multipart::new().with_text("name", name);
        if let Some(description) = description {
            form = form.with_text("description", description);
        }
        for (index, sample) in samples.iter().enumerate() {
            let bytes = sample.bytes(&*self.client).await?;
            let filename = sample.file_name(&format!("sample-{}", index + 1));
            form = form.with_file("files", filename, sample.content_type.as_str(), bytes);
        }
        let http = self
            .authorize(HttpRequest::post(format!(
                "{}/v1/voices/add",
                self.base_url
            )))
            .with_multipart(form);
        let response = self.client.send(http).await?.error_for_status()?;
        let created: CreatedVoice = response
            .json()
            .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
        Ok(created.voice_id)
    }

    /// Lists the voices of the account with `GET /v2/voices`, following the page tokens.
    async fn list_voices(&self) -> Result<Vec<VoiceInfo>, AudioError> {
        let mut voices = Vec::new();
        let mut token: Option<String> = None;
        loop {
            let mut path = "/v2/voices?page_size=100".to_string();
            if let Some(token) = &token {
                path.push_str("&next_page_token=");
                path.push_str(&percent_encode(token));
            }
            let response = self
                .client
                .send(self.get(&path))
                .await?
                .error_for_status()?;
            let page: VoicePage = response
                .json()
                .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
            voices.extend(page.voices.into_iter().map(|voice| {
                let info = VoiceInfo::new(voice.voice_id, voice.name)
                    .with_cloned(voice.category.as_deref() == Some("cloned"));
                match voice.description {
                    Some(description) => info.with_description(description),
                    None => info,
                }
            }));
            match page.next_page_token {
                Some(next) if page.has_more && token.as_ref() != Some(&next) => token = Some(next),
                _ => return Ok(voices),
            }
        }
    }

    /// Lists the models of `GET /v1/models` that can speak.
    async fn list_models(&self) -> Result<Vec<AudioModel>, AudioError> {
        let response = self
            .client
            .send(self.get("/v1/models"))
            .await?
            .error_for_status()?;
        let models: Vec<ModelEntry> = response
            .json()
            .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
        Ok(models
            .into_iter()
            .filter(|model| model.can_do_text_to_speech)
            .map(|entry| {
                let mut model =
                    AudioModel::new(format!("elevenlabs::{}", entry.model_id), entry.model_id);
                model.name = entry.name;
                model.description = entry.description;
                model
            })
            .collect())
    }
}

#[derive(Serialize)]
struct DesignBody<'a> {
    voice_description: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    text: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    auto_generate_text: Option<bool>,
}

#[derive(Deserialize)]
struct DesignResponse {
    previews: Vec<DesignPreview>,
    text: Option<String>,
}

#[derive(Deserialize)]
struct DesignPreview {
    generated_voice_id: String,
    audio_base_64: String,
    media_type: String,
}

#[derive(Serialize)]
struct SaveVoiceBody<'a> {
    voice_name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    voice_description: Option<&'a str>,
    generated_voice_id: &'a str,
}

#[derive(Deserialize)]
struct CreatedVoice {
    voice_id: String,
}

#[derive(Deserialize)]
struct VoicePage {
    #[serde(default)]
    voices: Vec<VoiceEntry>,
    #[serde(default)]
    has_more: bool,
    next_page_token: Option<String>,
}

#[derive(Deserialize)]
struct VoiceEntry {
    voice_id: String,
    #[serde(default)]
    name: String,
    category: Option<String>,
    description: Option<String>,
}

#[derive(Deserialize)]
struct ModelEntry {
    model_id: String,
    name: Option<String>,
    description: Option<String>,
    #[serde(default)]
    can_do_text_to_speech: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use agentai_core::HttpResponse;
    use agentai_core::message::Media;
    use agentai_core::mock::{MockHttp, body_json, json_response};
    use serde_json::json;

    fn provider(http: &MockHttp) -> ElevenLabsProvider {
        ElevenLabsProvider::new("eleven_v4", "key", "https://api.test")
            .with_client(Arc::new(http.clone()))
    }

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

    #[tokio::test]
    async fn generate_posts_to_the_voice_path() {
        let http = MockHttp::new(vec![audio()]);
        let r = provider(&http)
            .generate(
                SpeechRequest::new("hi")
                    .with_voice(Voice::id("abc123"))
                    .with_language("pl")
                    .with_speed(1.1),
            )
            .await
            .unwrap();
        let req = http.request(0);
        assert_eq!(req.url, "https://api.test/v1/text-to-speech/abc123");
        assert_eq!(req.header("xi-api-key"), Some("key"));
        assert_eq!(
            body_json(&req),
            json!({
                "text": "hi", "model_id": "eleven_v4", "language_code": "pl",
                "voice_settings": {"speed": 1.1}
            })
        );
        assert_eq!(r.audio.content_type, "audio/mpeg");
    }

    #[tokio::test]
    async fn formats_map_to_output_format() {
        let cases = [
            (AudioFormat::Pcm, "pcm_24000", "audio/pcm", Some(24000)),
            (AudioFormat::Mp3, "mp3_44100_128", "audio/mpeg", None),
            (AudioFormat::Wav, "wav_44100", "audio/wav", None),
            (AudioFormat::Opus, "opus_48000_128", "audio/ogg", None),
        ];
        for (format, query, content_type, rate) in cases {
            let http = MockHttp::new(vec![audio()]);
            let r = provider(&http)
                .generate(
                    SpeechRequest::new("hi")
                        .with_voice(Voice::id("v"))
                        .with_format(format),
                )
                .await
                .unwrap();
            assert!(
                http.request(0)
                    .url
                    .ends_with(&format!("?output_format={query}"))
            );
            assert_eq!(r.audio.content_type, content_type);
            assert_eq!(r.sample_rate, rate);
        }
        for format in [AudioFormat::Flac, AudioFormat::Aac] {
            let http = MockHttp::new(vec![]);
            let err = provider(&http)
                .generate(
                    SpeechRequest::new("hi")
                        .with_voice(Voice::id("v"))
                        .with_format(format),
                )
                .await
                .unwrap_err();
            assert!(matches!(err, AudioError::Unsupported(_)));
            assert_eq!(http.request_count(), 0);
        }
    }

    #[tokio::test]
    async fn the_output_format_override_wins_and_sets_the_type() {
        let http = MockHttp::new(vec![audio()]);
        let r = provider(&http)
            .with_output_format("pcm_16000")
            .generate(
                SpeechRequest::new("hi")
                    .with_voice(Voice::id("v"))
                    .with_format(AudioFormat::Mp3),
            )
            .await
            .unwrap();
        assert!(http.request(0).url.ends_with("?output_format=pcm_16000"));
        assert_eq!(r.audio.content_type, "audio/pcm");
        assert_eq!(r.sample_rate, Some(16000));
    }

    #[tokio::test]
    async fn unsafe_voice_ids_are_rejected_before_sending() {
        let http = MockHttp::new(vec![]);
        for id in ["../../v1/voices/x", "a/b", "a b", "..", ""] {
            let err = provider(&http)
                .generate(SpeechRequest::new("hi").with_voice(Voice::id(id)))
                .await
                .unwrap_err();
            assert!(matches!(err, AudioError::InvalidRequest(_)), "{id}");
        }
        assert_eq!(http.request_count(), 0);
    }

    #[tokio::test]
    async fn a_missing_voice_is_an_error() {
        let http = MockHttp::new(vec![]);
        let err = provider(&http)
            .generate(SpeechRequest::new("hi"))
            .await
            .unwrap_err();
        assert!(matches!(err, AudioError::MissingVoice));
        assert_eq!(http.request_count(), 0);
    }

    #[tokio::test]
    async fn create_voice_uploads_every_sample() {
        let http = MockHttp::new(vec![json_response(
            200,
            json!({"voice_id": "new1", "requires_verification": false}),
        )]);
        let samples = vec![
            Media::from_bytes("audio/wav", b"ONE").with_name("a.wav"),
            Media::from_bytes("audio/mpeg", b"TWO"),
        ];
        let id = provider(&http)
            .create_voice(
                "Adam",
                VoiceSource::samples(samples.clone(), None),
                Some("my voice"),
            )
            .await
            .unwrap();
        assert_eq!(id, "new1");

        let request = http.request(0);
        assert_eq!(request.url, "https://api.test/v1/voices/add");
        assert_eq!(request.header("xi-api-key"), Some("key"));
        let boundary = request
            .header("content-type")
            .unwrap()
            .strip_prefix("multipart/form-data; boundary=")
            .unwrap();
        let body = String::from_utf8(request.body.clone().unwrap()).unwrap();
        let field = |name: &str, value: &str| {
            format!("Content-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n")
        };
        let file = |filename: &str, content_type: &str, data: &str| {
            format!(
                "Content-Disposition: form-data; name=\"files\"; filename=\"{filename}\"\r\n\
                 Content-Type: {content_type}\r\n\r\n{data}\r\n"
            )
        };
        let parts: Vec<&str> = body
            .split(&format!("--{boundary}"))
            .map(|part| part.trim_start_matches("\r\n"))
            .collect();
        assert_eq!(
            parts,
            [
                "",
                &field("name", "Adam"),
                &field("description", "my voice"),
                &file("a.wav", "audio/wav", "ONE"),
                &file("sample-2.mp3", "audio/mpeg", "TWO"),
                "--\r\n",
            ]
        );

        let http = MockHttp::new(vec![]);
        let err = provider(&http)
            .create_voice("Adam", VoiceSource::samples(vec![], None), None)
            .await
            .unwrap_err();
        assert!(matches!(err, AudioError::InvalidRequest(_)));
        assert_eq!(http.request_count(), 0);
    }

    #[tokio::test]
    async fn list_voices_follows_the_token() {
        let http = MockHttp::new(vec![
            json_response(
                200,
                json!({
                    "voices": [{"voice_id": "v1", "name": "A", "category": "cloned", "description": "d"}],
                    "has_more": true, "next_page_token": "a+b"
                }),
            ),
            json_response(
                200,
                json!({
                    "voices": [{"voice_id": "v2", "name": "B", "category": "premade"}],
                    "has_more": false
                }),
            ),
        ]);
        let voices = provider(&http).list_voices().await.unwrap();
        assert_eq!(
            http.request(0).url,
            "https://api.test/v2/voices?page_size=100"
        );
        assert_eq!(
            http.request(1).url,
            "https://api.test/v2/voices?page_size=100&next_page_token=a%2Bb"
        );
        assert_eq!(
            voices,
            [
                VoiceInfo::new("v1", "A")
                    .with_description("d")
                    .with_cloned(true),
                VoiceInfo::new("v2", "B"),
            ]
        );
    }

    #[tokio::test]
    async fn models_keep_only_text_to_speech() {
        let http = MockHttp::new(vec![json_response(
            200,
            json!([
                {"model_id": "eleven_v4", "name": "V4", "can_do_text_to_speech": true},
                {"model_id": "scribe", "can_do_text_to_speech": false}
            ]),
        )]);
        let models = provider(&http).list_models().await.unwrap();
        assert_eq!(models.len(), 1);
        assert_eq!(models[0].model, "elevenlabs::eleven_v4");
        assert_eq!(models[0].id, "eleven_v4");
        assert_eq!(http.request(0).url, "https://api.test/v1/models");
    }

    #[tokio::test]
    async fn list_voices_stops_on_a_repeated_token() {
        let page = || {
            json_response(
                200,
                json!({
                    "voices": [{"voice_id": "v1", "name": "A"}],
                    "has_more": true, "next_page_token": "same"
                }),
            )
        };
        let http = MockHttp::new(vec![page(), page(), page(), page()]);
        let voices = provider(&http).list_voices().await.unwrap();
        assert_eq!(voices.len(), 2);
        assert_eq!(http.request_count(), 2);
    }

    #[tokio::test]
    async fn design_voice_returns_the_previews() {
        let http = MockHttp::new(vec![json_response(
            200,
            json!({"previews": [{"generated_voice_id": "g1",
                "audio_base_64": agentai_core::base64::encode(b"MP3"),
                "media_type": "audio/mpeg", "duration_secs": 2.0, "language": "en"}],
                "text": "Hello there"}),
        )]);
        let previews = provider(&http)
            .design_voice("warm low voice", Some("Hello there"), 3)
            .await
            .unwrap();
        let req = http.request(0);
        assert_eq!(req.url, "https://api.test/v1/text-to-voice/design");
        assert_eq!(req.header("xi-api-key"), Some("key"));
        assert_eq!(
            body_json(&req),
            json!({"voice_description": "warm low voice", "text": "Hello there"})
        );
        assert_eq!(
            previews,
            [VoicePreview::new(Media::from_bytes("audio/mpeg", b"MP3"))
                .with_text("Hello there")
                .with_sample_id("g1")]
        );
    }

    #[tokio::test]
    async fn design_voice_without_text_auto_generates_it() {
        let http = MockHttp::new(vec![json_response(200, json!({"previews": []}))]);
        provider(&http).design_voice("warm", None, 1).await.unwrap();
        assert_eq!(
            body_json(&http.request(0)),
            json!({"voice_description": "warm", "auto_generate_text": true})
        );
    }

    #[tokio::test]
    async fn create_voice_saves_a_designed_preview() {
        let http = MockHttp::new(vec![
            json_response(200, json!({"voice_id": "v9"})),
            json_response(200, json!({"voice_id": "v10"})),
        ]);
        let id = provider(&http)
            .create_voice(
                "Narrator",
                VoiceSource::SampleId("g1".into()),
                Some("warm low voice"),
            )
            .await
            .unwrap();
        assert_eq!(id, "v9");
        let req = http.request(0);
        assert_eq!(req.url, "https://api.test/v1/text-to-voice");
        assert_eq!(req.header("xi-api-key"), Some("key"));
        assert_eq!(
            body_json(&req),
            json!({"voice_name": "Narrator", "voice_description": "warm low voice",
                   "generated_voice_id": "g1"})
        );
        provider(&http)
            .create_voice("Narrator", VoiceSource::SampleId("g1".into()), None)
            .await
            .unwrap();
        assert_eq!(
            body_json(&http.request(1)),
            json!({"voice_name": "Narrator", "generated_voice_id": "g1"})
        );
    }
}