rig_core/providers/gemini/
audio_generation.rs1use 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
43pub const GEMINI_3_8_FLASH_TTS: &str = "gemini-3.8-flash-tts";
45pub const GEMINI_3_8_FLASH_LITE_TTS: &str = "gemini-3.8-flash-lite-tts";
47
48#[derive(Clone, Debug, Default, PartialEq, Eq)]
50pub struct Turn {
51 pub text: String,
54 pub speaker: Option<String>,
57 pub style: Option<String>,
59}
60
61impl Turn {
62 pub fn new(text: impl Into<String>) -> Self {
64 Self {
65 text: text.into(),
66 ..Self::default()
67 }
68 }
69
70 pub fn speaker(mut self, speaker: impl Into<String>) -> Self {
72 self.speaker = Some(speaker.into());
73 self
74 }
75
76 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 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#[non_exhaustive]
123#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
124pub enum AudioEncoding {
125 #[serde(rename = "audio/wav")]
127 Wav,
128 #[serde(rename = "audio/l16")]
131 L16,
132 #[serde(rename = "audio/mulaw")]
134 Mulaw,
135 #[serde(rename = "audio/alaw")]
137 Alaw,
138 #[serde(rename = "audio/mp3")]
140 Mp3,
141 #[serde(rename = "audio/ogg_opus")]
143 OggOpus,
144}
145
146#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
149pub struct AudioFormat {
150 #[serde(skip_serializing_if = "Option::is_none")]
152 pub mime_type: Option<AudioEncoding>,
153 #[serde(skip_serializing_if = "Option::is_none")]
155 pub sample_rate: Option<u32>,
156}
157
158impl AudioFormat {
159 pub fn new(encoding: AudioEncoding) -> Self {
161 Self {
162 mime_type: Some(encoding),
163 sample_rate: None,
164 }
165 }
166
167 pub fn pcm(sample_rate: u32) -> Self {
169 Self::new(AudioEncoding::L16).sample_rate(sample_rate)
170 }
171
172 pub fn sample_rate(mut self, hertz: u32) -> Self {
174 self.sample_rate = Some(hertz);
175 self
176 }
177}
178
179#[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
197fn input(turns: &[Turn]) -> Value {
199 json!([{ "type": "user_input", "content": turns }])
200}
201
202#[derive(Clone, Debug, PartialEq, Eq)]
206pub struct Script {
207 speech: InteractionSpeechConfig,
208 turns: Vec<Turn>,
209 format: Option<AudioFormat>,
210}
211
212impl Script {
213 pub fn voice(voice: impl Into<String>) -> Self {
215 Self::with(InteractionSpeechConfig::voice(InteractionSpeech::voice(
216 voice,
217 )))
218 }
219
220 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 pub fn with(speech: InteractionSpeechConfig) -> Self {
230 Self {
231 speech,
232 turns: Vec::new(),
233 format: None,
234 }
235 }
236
237 pub fn turn(mut self, turn: Turn) -> Self {
239 self.turns.push(turn);
240 self
241 }
242
243 pub fn format(mut self, format: AudioFormat) -> Self {
245 self.format = Some(format);
246 self
247 }
248
249 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
279fn 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#[derive(Clone, Debug, PartialEq, Eq)]
292pub struct SpeechFormat {
293 pub mime_type: Option<String>,
296 pub sample_rate: Option<u64>,
299 pub channels: Option<u64>,
301}
302
303pub 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#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
317pub struct Speech {
318 pub provider: super::GeminiConfig,
320 pub model: String,
322}
323
324impl Speech {
325 pub fn new(provider: super::GeminiConfig, model: impl Into<String>) -> Self {
327 Self {
328 provider,
329 model: model.into(),
330 }
331 }
332}
333
334fn 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 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 Ok(Encoded::new(request, Framing::Whole))
382 }
383
384 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
394fn 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 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;