Skip to main content

rig_core/providers/gemini/
transcription.rs

1use std::path::Path;
2
3use base64::{Engine, prelude::BASE64_STANDARD};
4use serde_json::{Map, Value, json};
5
6use super::completion::usage_of;
7use crate::error::{EncodeError, ProviderError};
8use crate::json_utils::Lenient;
9use crate::operation::Transcription;
10use crate::transcription;
11use crate::wire::{Body, Descriptor, DocumentDecoder, Encoded, Framing, Mode, Wire};
12
13const TRANSCRIPTION_PREAMBLE: &str =
14    "Translate the provided audio exactly. Do not add additional information.";
15
16/// Encode audio as inline base64, followed by the request's prompt, with a
17/// transcription system instruction naming the output language when one is
18/// set. Reject invalid generation parameters or JSON serialization failures.
19fn transcription_body(
20    request: transcription::TranscriptionRequest,
21) -> Result<Vec<u8>, EncodeError> {
22    let mut generation_config = match request.additional_params {
23        None | Some(Value::Null) => Map::new(),
24        Some(Value::Object(config)) => config,
25        Some(other) => {
26            return Err(EncodeError::request(format!(
27                "Gemini transcription `additional_params` should be an object, got {other}"
28            )));
29        }
30    };
31    // A temperature named on the request outranks one carried inside
32    // `additional_params`.
33    if let Some(temp) = request.temperature {
34        generation_config.insert("temperature".to_owned(), Value::from(temp));
35    }
36    // The request supplies no explicit MIME type, so infer it from the filename.
37    let mime_type = mime_guess::from_path(Path::new(&request.filename))
38        .first()
39        .map_or_else(|| "audio/mpeg".to_string(), |mime| mime.to_string());
40    let mut parts =
41        vec![json!({ "inlineData": { "mimeType": mime_type, "data": null }, "thought": false })];
42    parts.extend(
43        request
44            .prompt
45            .map(|prompt| json!({ "text": prompt, "thought": false })),
46    );
47    let mut instruction = vec![json!({ "text": TRANSCRIPTION_PREAMBLE, "thought": false })];
48    instruction.extend(request.language.map(|language| {
49        json!({ "text": format!("Use {language} as the output language."), "thought": false })
50    }));
51    let mut body = json!({
52        "contents": [{
53            "parts": parts,
54            "role": "user",
55        }],
56        "generationConfig": generation_config,
57        "safetySettings": null,
58        "toolConfig": null,
59        "systemInstruction": {
60            "parts": instruction,
61            "role": "model",
62        },
63    });
64    // The audio moves in: `json!` would copy it.
65    let data = body.pointer_mut("/contents/0/parts/0/inlineData/data");
66    *data.ok_or_else(|| EncodeError::request("the body has no slot for the audio"))? =
67        Value::String(BASE64_STANDARD.encode(request.data));
68    tracing::trace!(
69        target: "rig::transcription",
70        "Sending completion request to Gemini API {}",
71        serde_json::to_string_pretty(&body)?
72    );
73    Ok(serde_json::to_vec(&body)?)
74}
75
76/// The transcription wire: `POST /v1beta/models/{model}:generateContent`.
77///
78/// Both [`Mode`]s send inline audio in JSON and read a whole response.
79#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
80pub struct Transcriptions {
81    /// The provider this wire speaks to.
82    pub provider: super::GeminiConfig,
83    /// The model transcribing, for example
84    /// [`GEMINI_2_0_FLASH`](super::completion::GEMINI_2_0_FLASH).
85    pub model: String,
86}
87
88impl Transcriptions {
89    /// The transcription wire for `model`.
90    pub fn new(provider: super::GeminiConfig, model: impl Into<String>) -> Self {
91        Self {
92            provider,
93            model: model.into(),
94        }
95    }
96}
97
98impl Wire for Transcriptions {
99    type Op = Transcription;
100    type Payload = crate::wire::Encoded;
101    type Frame = crate::wire::WireFrame;
102    type Event = Value;
103    type Decoder<'id> = DocumentDecoder<Transcription, Value>;
104    type Reassembler = crate::wire::document::Unreassembled;
105
106    fn describe(&self) -> Descriptor<'_> {
107        Descriptor::new(super::PROVIDER_NAME).model(self.model.as_str())
108    }
109
110    fn encode(
111        &self,
112        request: transcription::TranscriptionRequest,
113        _mode: Mode,
114    ) -> Result<Encoded, EncodeError> {
115        let body = transcription_body(request)?;
116        let path = format!("/v1beta/models/{}:generateContent", self.model);
117        let request = self.provider.post_json(&path, Body::Bytes(body))?;
118        // Gemini reports no transport request-id header.
119        Ok(Encoded::new(request, Framing::Whole))
120    }
121
122    /// The first candidate's visible text; missing candidates or text are
123    /// response errors.
124    fn decoder<'id>(&self) -> Self::Decoder<'id> {
125        DocumentDecoder::new(super::completion::classify_reply, |reply| {
126            transcript_of(&reply)
127        })
128    }
129}
130
131/// The first candidate's visible text parts, those not marked `thought`, as
132/// a transcript of `reply`. Errors when there is no candidate or no visible
133/// text part.
134pub fn transcript_of(reply: &Value) -> Result<transcription::TranscriptionResponse, ProviderError> {
135    let candidate = reply
136        .arr("candidates")
137        .first()
138        .ok_or_else(|| ProviderError::Response("No response candidates in response".into()))?;
139    let parts: Vec<&str> = candidate
140        .get("content")
141        .map(|content| content.arr("parts"))
142        .unwrap_or_default()
143        .iter()
144        .filter(|part| part.bool("thought") != Some(true))
145        .filter_map(|part| part.str("text"))
146        .collect();
147    if parts.is_empty() {
148        return Err(ProviderError::Response(
149            "Response content contains no text".to_string(),
150        ));
151    }
152    Ok(transcription::TranscriptionResponse {
153        model: reply.str("modelVersion").map(str::to_owned),
154        response_id: reply.str("responseId").map(str::to_owned),
155        usage: reply.get("usageMetadata").map(usage_of).unwrap_or_default(),
156        ..transcription::TranscriptionResponse::new(parts.concat())
157    })
158}
159
160impl super::GeminiConfig {
161    /// The audio transcription wire.
162    pub(crate) fn transcription(&self, model: impl Into<String>) -> Transcriptions {
163        Transcriptions::new(self.clone(), model)
164    }
165}
166
167#[cfg(test)]
168mod tests;