Skip to main content

gemini_genai_rs/protocol/messages/
client.rs

1//! Client → Server message types for the Gemini Live wire protocol.
2
3use serde::{Deserialize, Serialize};
4
5use crate::protocol::types::*;
6
7/// Top-level setup message sent immediately after WebSocket connect.
8#[derive(Debug, Clone, Serialize)]
9pub struct SetupMessage {
10    /// The setup payload.
11    pub setup: SetupPayload,
12}
13
14/// Payload of the setup message.
15#[derive(Debug, Clone, Serialize)]
16#[serde(rename_all = "camelCase")]
17pub struct SetupPayload {
18    /// Model URI string (e.g. `"models/gemini-2.0-flash-live-001"`).
19    pub model: String,
20    /// Generation parameters (modalities, temperature, etc.).
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub generation_config: Option<GenerationConfig>,
23    /// System instruction content.
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub system_instruction: Option<Content>,
26    /// Tool declarations for function calling, search, etc.
27    #[serde(skip_serializing_if = "Vec::is_empty")]
28    pub tools: Vec<Tool>,
29    /// Tool usage configuration.
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub tool_config: Option<ToolConfig>,
32    /// Enable input audio transcription.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub input_audio_transcription: Option<InputAudioTranscription>,
35    /// Enable output audio transcription.
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub output_audio_transcription: Option<OutputAudioTranscription>,
38    /// Realtime input configuration (VAD, activity handling).
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub realtime_input_config: Option<RealtimeInputConfig>,
41    /// Session resumption configuration.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub session_resumption: Option<SessionResumptionConfig>,
44    /// Context window compression configuration.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub context_window_compression: Option<ContextWindowCompressionConfig>,
47    /// Proactivity configuration.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub proactivity: Option<ProactivityConfig>,
50    /// Ask for explicit `voiceActivity` events (Vertex AI).
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub explicit_vad_signal: Option<bool>,
53    /// How `clientContent` history is treated.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub history_config: Option<HistoryConfig>,
56    /// Live Avatar video output.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub avatar_config: Option<AvatarConfig>,
59}
60
61impl SessionConfig {
62    /// Build the setup message from this configuration.
63    ///
64    /// Settings the target does not accept are left off the wire rather
65    /// than failing the handshake; [`SessionConfig::ignored_settings`] lists
66    /// exactly what this drops:
67    ///
68    /// - `behavior` on function declarations, on Vertex AI models without
69    ///   async tool calling;
70    /// - `thinkingConfig` on Vertex AI and on models without thinking;
71    /// - `enableAffectiveDialog` and `proactivity` on models where both are
72    ///   always on (Gemini 3.8 Live);
73    /// - on Google AI, which has no such fields: `proactivity`,
74    ///   `explicitVadSignal`, `sessionResumption.transparent`, and
75    ///   `avatarConfig.avatarName` / `customizedAvatar`.
76    pub fn to_setup_message(&self) -> SetupMessage {
77        let profile = self.model_profile();
78        let tools = self.wire_tools(&self.tools);
79
80        let mut generation_config = self.generation_config.clone();
81        let mut output_audio_transcription = self.output_audio_transcription.clone();
82        if self.text_via_transcription() {
83            generation_config.response_modalities = Some(vec![Modality::Audio]);
84            output_audio_transcription.get_or_insert_with(Default::default);
85        }
86        if !self.supports_thinking() {
87            generation_config.thinking_config = None;
88        }
89        if !profile.affective_dialog_flag {
90            generation_config.enable_affective_dialog = None;
91        }
92
93        SetupMessage {
94            setup: SetupPayload {
95                model: self.model_uri(),
96                generation_config: Some(generation_config),
97                system_instruction: self.system_instruction.clone(),
98                tools,
99                tool_config: self.tool_config.clone(),
100                input_audio_transcription: self.input_audio_transcription.clone(),
101                output_audio_transcription,
102                realtime_input_config: self.realtime_input_config.clone(),
103                session_resumption: self.session_resumption.clone().map(|mut r| {
104                    if !self.is_vertex() {
105                        r.transparent = None;
106                    }
107                    r
108                }),
109                context_window_compression: self.context_window_compression.clone(),
110                proactivity: self
111                    .proactivity
112                    .clone()
113                    .filter(|_| self.is_vertex() && profile.proactivity_flag),
114                explicit_vad_signal: self.explicit_vad_signal.filter(|_| self.is_vertex()),
115                history_config: self.history_config.clone(),
116                avatar_config: self.avatar_config.clone().map(|mut a| {
117                    if !self.is_vertex() {
118                        a.avatar_name = None;
119                        a.customized_avatar = None;
120                    }
121                    a
122                }),
123            },
124        }
125    }
126
127    /// Pre-serialize the setup message to JSON. Called once at connection time.
128    pub fn to_setup_json(&self) -> String {
129        serde_json::to_string(&self.to_setup_message())
130            .expect("setup message serialization is infallible for valid config")
131    }
132
133    /// Build the `contextUpdate` message for `update`, with tools shaped
134    /// for this target the same way the setup message shapes them.
135    pub fn to_context_update_message(&self, update: &ContextUpdate) -> ContextUpdateMessage {
136        ContextUpdateMessage {
137            context_update: ContextUpdatePayload {
138                system_instruction: update.system_instruction.clone(),
139                tools: update.tools.as_ref().map(|tools| ContextUpdateTools {
140                    tools: self.wire_tools(tools),
141                }),
142            },
143        }
144    }
145
146    /// Fold `update` into this configuration, so the next setup message (on
147    /// a reconnect) declares the current tools and instruction rather than
148    /// the ones the session started with. The session loop calls this when
149    /// it sends an update.
150    pub fn apply_context_update(&mut self, update: &ContextUpdate) {
151        if let Some(instruction) = &update.system_instruction {
152            self.system_instruction = Some(instruction.clone());
153        }
154        if let Some(tools) = &update.tools {
155            self.tools = tools.clone();
156        }
157    }
158
159    /// `tools` as this target accepts them: `behavior` is removed from
160    /// function declarations where async tool calling is not supported.
161    fn wire_tools(&self, tools: &[Tool]) -> Vec<Tool> {
162        let async_tools = self.supports_async_tools();
163        let code_execution = self.supports_code_execution();
164        tools
165            .iter()
166            .filter_map(|tool| {
167                let mut t = tool.clone();
168                if !async_tools && let Some(ref mut decls) = t.function_declarations {
169                    for d in decls.iter_mut() {
170                        d.behavior = None;
171                    }
172                }
173                if !code_execution && t.code_execution.take().is_some() {
174                    // A tool entry that only carried code execution goes.
175                    let other = t.function_declarations.is_some()
176                        || t.google_search.is_some()
177                        || t.google_search_retrieval.is_some()
178                        || t.url_context.is_some();
179                    return other.then_some(t);
180                }
181                Some(t)
182            })
183            .collect()
184    }
185}
186
187/// Realtime audio input sent as a stream of chunks.
188#[derive(Debug, Clone, Serialize)]
189#[serde(rename_all = "camelCase")]
190pub struct RealtimeInputMessage {
191    /// The realtime input payload.
192    pub realtime_input: RealtimeInputPayload,
193}
194
195/// Payload for realtime audio input.
196#[derive(Debug, Clone, Serialize)]
197#[serde(rename_all = "camelCase")]
198pub struct RealtimeInputPayload {
199    /// Deprecated: use `audio` instead. Kept for backward compatibility.
200    #[serde(skip_serializing_if = "Vec::is_empty")]
201    pub media_chunks: Vec<MediaChunk>,
202    /// Audio input blob (preferred over media_chunks).
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub audio: Option<Blob>,
205    /// Video input blob.
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub video: Option<Blob>,
208    /// Signal end of audio stream.
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub audio_stream_end: Option<bool>,
211    /// Realtime text input (streamed inline, distinct from clientContent).
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub text: Option<String>,
214}
215
216/// A single chunk of media data (audio). Deprecated — use Blob in `audio` field.
217#[derive(Debug, Clone, Serialize)]
218#[serde(rename_all = "camelCase")]
219pub struct MediaChunk {
220    /// MIME type of the media (e.g. `"audio/pcm"`).
221    pub mime_type: String,
222    /// Base64-encoded media data.
223    pub data: String, // base64-encoded
224}
225
226/// Client content message for sending text or conversation history.
227#[derive(Debug, Clone, Serialize)]
228#[serde(rename_all = "camelCase")]
229pub struct ClientContentMessage {
230    /// The client content payload.
231    pub client_content: ClientContentPayload,
232}
233
234/// Payload for client content.
235#[derive(Debug, Clone, Serialize)]
236#[serde(rename_all = "camelCase")]
237pub struct ClientContentPayload {
238    /// Conversation turns to send.
239    pub turns: Vec<Content>,
240    /// Whether this completes the client's turn.
241    #[serde(skip_serializing_if = "Option::is_none")]
242    pub turn_complete: Option<bool>,
243}
244
245/// Tool response message sent after executing function calls.
246#[derive(Debug, Clone, Serialize)]
247#[serde(rename_all = "camelCase")]
248pub struct ToolResponseMessage {
249    /// The tool response payload.
250    pub tool_response: ToolResponsePayload,
251}
252
253/// Payload for tool response.
254#[derive(Debug, Clone, Serialize)]
255#[serde(rename_all = "camelCase")]
256pub struct ToolResponsePayload {
257    /// Function call responses to return to the model.
258    pub function_responses: Vec<FunctionResponse>,
259}
260
261/// Mid-session preamble update message (`contextUpdate`).
262#[derive(Debug, Clone, Serialize)]
263#[serde(rename_all = "camelCase")]
264pub struct ContextUpdateMessage {
265    /// The context update payload.
266    pub context_update: ContextUpdatePayload,
267}
268
269/// Payload of a `contextUpdate` message. Unset fields are left off the wire,
270/// which is what keeps their current values on the server.
271#[derive(Debug, Clone, Serialize)]
272#[serde(rename_all = "camelCase")]
273pub struct ContextUpdatePayload {
274    /// Replacement system instruction.
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub system_instruction: Option<Content>,
277    /// Replacement tool list.
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub tools: Option<ContextUpdateTools>,
280}
281
282/// The `tools` wrapper of a `contextUpdate`. Its presence means "replace":
283/// the list is always serialized, so an empty list clears every tool.
284#[derive(Debug, Clone, Serialize)]
285pub struct ContextUpdateTools {
286    /// The complete replacement tool list.
287    pub tools: Vec<Tool>,
288}
289
290/// Activity signal for client-side VAD events.
291#[derive(Debug, Clone, Serialize)]
292#[serde(rename_all = "camelCase")]
293pub struct ActivitySignalMessage {
294    /// The activity signal payload.
295    pub realtime_input: ActivitySignalPayload,
296}
297
298/// Payload for activity signals.
299#[derive(Debug, Clone, Serialize)]
300#[serde(rename_all = "camelCase")]
301pub struct ActivitySignalPayload {
302    /// Present when signaling activity start.
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub activity_start: Option<ActivityStart>,
305    /// Present when signaling activity end.
306    #[serde(skip_serializing_if = "Option::is_none")]
307    pub activity_end: Option<ActivityEnd>,
308}
309
310/// Marker for speech activity start.
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct ActivityStart {}
313
314/// Marker for speech activity end.
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct ActivityEnd {}