Skip to main content

rig_core/providers/gemini/
audio_generation.rs

1//! Text-to-speech through the Interactions API. A request speaks its text
2//! in its voice; a [`Script`] speaks turns, each with an optional speaker
3//! and style, in one voice or one voice per speaker. [`format_of`] reads the
4//! format of the audio a reply carries.
5//!
6//! ```no_run
7//! use rig_core::audio_generation::AudioGenerationRequestBuilder;
8//! use rig_core::providers::gemini::Gemini;
9//! use rig_core::providers::gemini::audio_generation::{
10//!     AudioFormat, GEMINI_3_8_FLASH_TTS, Script, Turn,
11//! };
12//!
13//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
14//! let model = Gemini::from_env()?.audio_generation(GEMINI_3_8_FLASH_TTS);
15//! let hello = AudioGenerationRequestBuilder::new("Have a wonderful day!", "Kore").build();
16//! let wav = model.call(hello).await?.audio;
17//!
18//! let podcast = Script::speakers([("Joe", "Puck"), ("Jane", "Kore")])
19//!     .turn(Turn::new("How's it going, Jane?").speaker("Joe").style("cheerful"))
20//!     .turn(Turn::new("Not bad at all.").speaker("Jane"))
21//!     .format(AudioFormat::pcm(24_000))
22//!     .build();
23//! let pcm = model.call(podcast).await?.audio;
24//! # let _ = (wav, pcm);
25//! # Ok(())
26//! # }
27//! ```
28
29use base64::Engine;
30use base64::prelude::BASE64_STANDARD;
31use serde::Serialize;
32use serde_json::{Value, json};
33
34use super::interactions_api::streaming::usage_of;
35use super::interactions_api::{InteractionSpeech, InteractionSpeechConfig};
36use crate::audio_generation::{AudioGenerationRequest, AudioGenerationResponse};
37use crate::error::{EncodeError, ProviderError};
38use crate::json_utils::Lenient;
39use crate::operation::AudioGeneration;
40use crate::providers::internal::wire::classify_marker_keyed_frame;
41use crate::wire::{Descriptor, DocumentDecoder, Encoded, Framing, Mode, Wire, WireFrame};
42
43/// `gemini-3.8-flash-tts`: the most expressive speech model.
44pub const GEMINI_3_8_FLASH_TTS: &str = "gemini-3.8-flash-tts";
45/// `gemini-3.8-flash-lite-tts`: the fast, low-cost speech model.
46pub const GEMINI_3_8_FLASH_LITE_TTS: &str = "gemini-3.8-flash-lite-tts";
47
48/// One turn of a [`Script`]: its text, read verbatim, and how to read it.
49#[derive(Clone, Debug, Default, PartialEq, Eq)]
50pub struct Turn {
51    /// The words to speak. Inline tags such as `<laugh>` mark momentary
52    /// sounds.
53    pub text: String,
54    /// The speaker, one of the script's speakers. Every turn of a
55    /// multi-speaker script names one.
56    pub speaker: Option<String>,
57    /// How the whole turn sounds, such as `"whispered urgently"`.
58    pub style: Option<String>,
59}
60
61impl Turn {
62    /// A turn that speaks `text`.
63    pub fn new(text: impl Into<String>) -> Self {
64        Self {
65            text: text.into(),
66            ..Self::default()
67        }
68    }
69
70    /// The speaker.
71    pub fn speaker(mut self, speaker: impl Into<String>) -> Self {
72        self.speaker = Some(speaker.into());
73        self
74    }
75
76    /// The style.
77    pub fn style(mut self, style: impl Into<String>) -> Self {
78        self.style = Some(style.into());
79        self
80    }
81}
82
83impl Serialize for Turn {
84    /// A text content item, with a `speech_metadata` annotation when the
85    /// turn names a speaker or a style.
86    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
87        #[derive(Serialize)]
88        struct Metadata<'a> {
89            #[serde(rename = "type")]
90            kind: &'static str,
91            #[serde(skip_serializing_if = "Option::is_none")]
92            speaker: Option<&'a str>,
93            #[serde(skip_serializing_if = "Option::is_none")]
94            style: Option<&'a str>,
95        }
96        #[derive(Serialize)]
97        struct Text<'a> {
98            #[serde(rename = "type")]
99            kind: &'static str,
100            text: &'a str,
101            #[serde(skip_serializing_if = "Vec::is_empty")]
102            annotations: Vec<Metadata<'a>>,
103        }
104        let annotations = match (&self.speaker, &self.style) {
105            (None, None) => Vec::new(),
106            (speaker, style) => vec![Metadata {
107                kind: "speech_metadata",
108                speaker: speaker.as_deref(),
109                style: style.as_deref(),
110            }],
111        };
112        Text {
113            kind: "text",
114            text: &self.text,
115            annotations,
116        }
117        .serialize(serializer)
118    }
119}
120
121/// The encoding of the audio a reply carries.
122#[non_exhaustive]
123#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
124pub enum AudioEncoding {
125    /// `audio/wav`, the API's default: 16-bit PCM with a RIFF header.
126    #[serde(rename = "audio/wav")]
127    Wav,
128    /// `audio/l16`: headerless 16-bit signed little-endian PCM, which
129    /// joins by concatenation.
130    #[serde(rename = "audio/l16")]
131    L16,
132    /// `audio/mulaw`: 8-bit G.711 mu-law.
133    #[serde(rename = "audio/mulaw")]
134    Mulaw,
135    /// `audio/alaw`: 8-bit G.711 A-law.
136    #[serde(rename = "audio/alaw")]
137    Alaw,
138    /// `audio/mp3`.
139    #[serde(rename = "audio/mp3")]
140    Mp3,
141    /// `audio/ogg_opus`.
142    #[serde(rename = "audio/ogg_opus")]
143    OggOpus,
144}
145
146/// The audio format to answer in: the request's `response_format`. A field
147/// left unset takes the API's default.
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
149pub struct AudioFormat {
150    /// `mime_type`.
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub mime_type: Option<AudioEncoding>,
153    /// `sample_rate`, in hertz.
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub sample_rate: Option<u32>,
156}
157
158impl AudioFormat {
159    /// Audio in `encoding`.
160    pub fn new(encoding: AudioEncoding) -> Self {
161        Self {
162            mime_type: Some(encoding),
163            sample_rate: None,
164        }
165    }
166
167    /// Headerless PCM ([`AudioEncoding::L16`]) at `sample_rate` hertz.
168    pub fn pcm(sample_rate: u32) -> Self {
169        Self::new(AudioEncoding::L16).sample_rate(sample_rate)
170    }
171
172    /// `sample_rate`, in hertz.
173    pub fn sample_rate(mut self, hertz: u32) -> Self {
174        self.sample_rate = Some(hertz);
175        self
176    }
177}
178
179/// `response_format` for audio.
180#[derive(Serialize)]
181struct ResponseFormat {
182    #[serde(rename = "type")]
183    kind: &'static str,
184    #[serde(flatten)]
185    format: AudioFormat,
186}
187
188impl From<AudioFormat> for ResponseFormat {
189    fn from(format: AudioFormat) -> Self {
190        Self {
191            kind: "audio",
192            format,
193        }
194    }
195}
196
197/// One `user_input` step of `turns`.
198fn input(turns: &[Turn]) -> Value {
199    json!([{ "type": "user_input", "content": turns }])
200}
201
202/// Turns spoken in one voice or one voice per speaker, in a format: a
203/// speech request [`build`](Self::build) turns into an
204/// [`AudioGenerationRequest`] for the [`Speech`] wire.
205#[derive(Clone, Debug, PartialEq, Eq)]
206pub struct Script {
207    speech: InteractionSpeechConfig,
208    turns: Vec<Turn>,
209    format: Option<AudioFormat>,
210}
211
212impl Script {
213    /// A script spoken in `voice`, such as `"Kore"` or a custom voice id.
214    pub fn voice(voice: impl Into<String>) -> Self {
215        Self::with(InteractionSpeechConfig::voice(InteractionSpeech::voice(
216            voice,
217        )))
218    }
219
220    /// A script whose turns each speaker of the `(speaker, voice)` pairs
221    /// speaks in its voice. The API takes up to two speakers.
222    pub fn speakers<S: Into<String>, V: Into<String>>(
223        speakers: impl IntoIterator<Item = (S, V)>,
224    ) -> Self {
225        Self::with(InteractionSpeechConfig::speakers(speakers))
226    }
227
228    /// A script spoken as `speech` configures.
229    pub fn with(speech: InteractionSpeechConfig) -> Self {
230        Self {
231            speech,
232            turns: Vec::new(),
233            format: None,
234        }
235    }
236
237    /// Add a turn.
238    pub fn turn(mut self, turn: Turn) -> Self {
239        self.turns.push(turn);
240        self
241    }
242
243    /// The audio format.
244    pub fn format(mut self, format: AudioFormat) -> Self {
245        self.format = Some(format);
246        self
247    }
248
249    /// The request that speaks this script. Its text is the turns' text,
250    /// one per line, and its `additional_params` carry the turns, the
251    /// voices and the format.
252    pub fn build(self) -> AudioGenerationRequest {
253        let text = self
254            .turns
255            .iter()
256            .map(|turn| turn.text.as_str())
257            .collect::<Vec<_>>()
258            .join("\n");
259        let voice = match &self.speech {
260            InteractionSpeechConfig::Voice([voice]) => voice.voice.clone().unwrap_or_default(),
261            InteractionSpeechConfig::Speakers { .. } => String::new(),
262        };
263        let mut params = json!({
264            "input": input(&self.turns),
265            "generation_config": { "speech_config": self.speech },
266        });
267        if let (Some(format), Some(fields)) = (self.format, params.as_object_mut()) {
268            fields.insert(
269                "response_format".to_owned(),
270                json!(ResponseFormat::from(format)),
271            );
272        }
273        crate::audio_generation::AudioGenerationRequestBuilder::new(text, voice)
274            .additional_params(params)
275            .build()
276    }
277}
278
279/// The audio content item a reply ends with: the last `audio` item of its
280/// model output steps.
281fn last_audio(reply: &Value) -> Option<&Value> {
282    reply
283        .arr("steps")
284        .iter()
285        .filter(|step| step.str("type") == Some("model_output"))
286        .flat_map(|step| step.arr("content"))
287        .rfind(|content| content.str("type") == Some("audio"))
288}
289
290/// The format of the audio a reply carries, as the API states it.
291#[derive(Clone, Debug, PartialEq, Eq)]
292pub struct SpeechFormat {
293    /// The media type, with its parameters, such as
294    /// `audio/l16; rate=24000; channels=1`.
295    pub mime_type: Option<String>,
296    /// The sample rate in hertz, which the API states for headerless
297    /// audio.
298    pub sample_rate: Option<u64>,
299    /// The number of channels, which the API states for headerless audio.
300    pub channels: Option<u64>,
301}
302
303/// The format of the audio in `response`, read from its reply document.
304pub fn format_of(response: &AudioGenerationResponse) -> Option<SpeechFormat> {
305    let audio = last_audio(&response.raw)?;
306    Some(SpeechFormat {
307        mime_type: audio.str("mime_type").map(str::to_owned),
308        sample_rate: audio.u64("sample_rate"),
309        channels: audio.u64("channels"),
310    })
311}
312
313/// The text-to-speech wire: `POST /v1beta/interactions` with audio output.
314///
315/// Both [`Mode`]s send a unary request and decode the whole interaction.
316#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
317pub struct Speech {
318    /// The provider this wire speaks to.
319    pub provider: super::GeminiConfig,
320    /// Name of the model, for example [`GEMINI_3_8_FLASH_TTS`].
321    pub model: String,
322}
323
324impl Speech {
325    /// The text-to-speech wire for `model`.
326    pub fn new(provider: super::GeminiConfig, model: impl Into<String>) -> Self {
327        Self {
328            provider,
329            model: model.into(),
330        }
331    }
332}
333
334/// The interaction `request` creates: its text as one turn in its voice,
335/// with `additional_params` merged over it key by key. An `input` there,
336/// such as a [`Script`]'s, takes the place of the text.
337fn create_request_body(model: &str, request: AudioGenerationRequest) -> Value {
338    let mut body = json!({
339        "model": model,
340        "input": input(&[Turn::new(request.text)]),
341        "response_format": ResponseFormat::from(AudioFormat::default()),
342    });
343    if let (false, Some(fields)) = (request.voice.is_empty(), body.as_object_mut()) {
344        let speech = InteractionSpeechConfig::voice(InteractionSpeech::voice(request.voice));
345        fields.insert(
346            "generation_config".to_owned(),
347            json!({ "speech_config": speech }),
348        );
349    }
350    super::apply_params(&mut body, request.additional_params);
351    body
352}
353
354impl Wire for Speech {
355    type Op = AudioGeneration;
356    type Payload = Encoded;
357    type Frame = WireFrame;
358    type Event = Value;
359    type Decoder<'id> = DocumentDecoder<AudioGeneration, Value>;
360    type Reassembler = crate::wire::document::Unreassembled;
361
362    fn describe(&self) -> Descriptor<'_> {
363        Descriptor::new(super::PROVIDER_NAME).model(self.model.as_str())
364    }
365
366    /// # Errors
367    ///
368    /// When the request asks for a speed other than 1.0: the API has none,
369    /// and a turn's style sets the pace instead.
370    fn encode(&self, request: AudioGenerationRequest, _mode: Mode) -> Result<Encoded, EncodeError> {
371        if request.speed != 1.0 {
372            return Err(EncodeError::request(
373                "Gemini speech takes no speed; ask for the pace in a turn's style",
374            ));
375        }
376        let body = serde_json::to_vec(&create_request_body(&self.model, request))?;
377        let request = self
378            .provider
379            .post_json("/v1beta/interactions", crate::wire::Body::Bytes(body))?;
380        // Gemini reports no transport request-id header.
381        Ok(Encoded::new(request, Framing::Whole))
382    }
383
384    /// The last audio item of an interaction, with its usage and identity.
385    /// An interaction with no inline audio is a response error.
386    fn decoder<'id>(&self) -> Self::Decoder<'id> {
387        DocumentDecoder::new(
388            |body| classify_marker_keyed_frame(body, &["steps", "status", "usage", "id"]),
389            speech_of,
390        )
391    }
392}
393
394/// The speech an interaction carried.
395fn speech_of(event: Value) -> Result<AudioGenerationResponse, ProviderError> {
396    let data = last_audio(&event)
397        .and_then(|audio| audio.str("data"))
398        .ok_or_else(|| {
399            ProviderError::Response(format!(
400                "the Gemini speech interaction ({}) carried no inline audio",
401                event.str("status").unwrap_or("no status")
402            ))
403        })?;
404    let audio = BASE64_STANDARD.decode(data).map_err(|err| {
405        ProviderError::Response(format!("Gemini audio data was not valid base64: {err}"))
406    })?;
407    Ok(AudioGenerationResponse {
408        model: event.str("model").map(str::to_owned),
409        response_id: event.str("id").map(str::to_owned),
410        usage: event
411            .get("usage")
412            .map(usage_of)
413            .transpose()?
414            .unwrap_or_default(),
415        ..AudioGenerationResponse::new(audio)
416    })
417}
418
419impl super::GeminiConfig {
420    /// The text-to-speech wire.
421    pub(crate) fn audio_generation(&self, model: impl Into<String>) -> Speech {
422        Speech::new(self.clone(), model)
423    }
424}
425
426#[cfg(test)]
427mod tests;