adk-gemini 0.7.0

Rust client for Google Gemini API
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
//! # Core Gemini API Primitives
//!
//! This module contains the fundamental building blocks used across the Gemini API.
//! These core data structures are shared by multiple modules and form the foundation
//! for constructing requests and parsing responses.
//!
//! ## Core Types
//!
//! - [`Role`] - Represents the speaker in a conversation (User or Model)
//! - [`Part`] - Content fragments that make up messages (text, images, function calls)
//! - [`Blob`] - Binary data with MIME type for inline content
//! - [`Content`] - Container for parts with optional role assignment
//! - [`Message`] - Complete message with content and explicit role
//! - [`Modality`] - Output format types (text, image, audio)
//!
//! ## Usage
//!
//! These types are typically used in combination with the domain-specific modules:
//! - `generation` - For content generation requests and responses
//! - `embedding` - For text embedding operations
//! - `safety` - For content moderation settings
//! - `tools` - For function calling capabilities
//! - `batch` - For batch processing operations
//! - `cache` - For content caching
//! - `files` - For file management

#![allow(clippy::enum_variant_names)]

use serde::{Deserialize, Serialize, de};

/// Role of a message in a conversation
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    /// Message from the user
    User,
    /// Message from the model
    Model,
}

/// Content part that can be included in a message
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum Part {
    /// Text content
    Text {
        /// The text content
        text: String,
        /// Whether this is a thought summary (Gemini 2.5 series only)
        #[serde(skip_serializing_if = "Option::is_none")]
        thought: Option<bool>,
        /// The thought signature (Gemini 2.5+ thinking models only).
        /// Preserved from responses and echoed back in conversation history for Gemini 3.x thought signature support.
        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
        thought_signature: Option<String>,
    },
    InlineData {
        /// The blob data
        #[serde(rename = "inlineData")]
        inline_data: Blob,
    },
    /// File data referenced by URI
    FileData {
        #[serde(rename = "fileData")]
        file_data: FileDataRef,
    },
    /// Function call from the model
    FunctionCall {
        /// The function call details
        #[serde(rename = "functionCall")]
        function_call: super::tools::FunctionCall,
        /// The thought signature (Gemini 2.5+ thinking models only).
        /// Preserved from responses and echoed back in conversation history for Gemini 3.x thought signature support.
        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
        thought_signature: Option<String>,
    },
    /// Function response (results from executing a function call)
    FunctionResponse {
        /// The function response details
        #[serde(rename = "functionResponse")]
        function_response: super::tools::FunctionResponse,
        /// The thought signature (Gemini 3.x thinking models).
        /// Must be echoed back on function response parts when thinking is active.
        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
        thought_signature: Option<String>,
    },
    /// Server-side tool call from Gemini 3 (built-in tool invocation)
    ToolCall {
        #[serde(rename = "toolCall")]
        tool_call: serde_json::Value,
        /// The thought signature (Gemini 3.x thinking models).
        /// Must be preserved and echoed back in conversation history.
        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
        thought_signature: Option<String>,
    },
    /// Server-side tool response from Gemini 3 (built-in tool result)
    ToolResponse {
        #[serde(rename = "toolResponse")]
        tool_response: serde_json::Value,
        /// The thought signature (Gemini 3.x thinking models).
        /// Must be preserved and echoed back in conversation history.
        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
        thought_signature: Option<String>,
    },
    /// Generated code emitted by Gemini code execution.
    ExecutableCode {
        #[serde(rename = "executableCode")]
        executable_code: serde_json::Value,
        /// The thought signature (Gemini 3.x thinking models).
        /// Must be preserved and echoed back in conversation history.
        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
        thought_signature: Option<String>,
    },
    /// Result emitted by Gemini code execution.
    CodeExecutionResult {
        #[serde(rename = "codeExecutionResult")]
        code_execution_result: serde_json::Value,
        /// The thought signature (Gemini 3.x thinking models).
        /// Must be preserved and echoed back in conversation history.
        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
        thought_signature: Option<String>,
    },
}

/// Blob for a message part
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Blob {
    /// The MIME type of the data
    pub mime_type: String,
    /// Base64 encoded data
    pub data: String,
}

impl Blob {
    /// Create a new blob with mime type and data
    pub fn new(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
        Self { mime_type: mime_type.into(), data: data.into() }
    }
}

/// Reference to an external file by URI, used in Gemini wire format.
///
/// # Example
///
/// ```rust
/// use adk_gemini::FileDataRef;
///
/// let file_ref = FileDataRef {
///     mime_type: "application/pdf".to_string(),
///     file_uri: "gs://my-bucket/report.pdf".to_string(),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FileDataRef {
    pub mime_type: String,
    pub file_uri: String,
}

/// Content of a message
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Content {
    /// Parts of the content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parts: Option<Vec<Part>>,
    /// Role of the content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<Role>,
}

impl Content {
    /// Create a new text content
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            parts: Some(vec![Part::Text {
                text: text.into(),
                thought: None,
                thought_signature: None,
            }]),
            role: None,
        }
    }

    /// Create a new content with a function call
    pub fn function_call(function_call: super::tools::FunctionCall) -> Self {
        Self {
            parts: Some(vec![Part::FunctionCall { function_call, thought_signature: None }]),
            role: None,
        }
    }

    /// Create a new content with a function call and thought signature
    pub fn function_call_with_thought(
        function_call: super::tools::FunctionCall,
        thought_signature: impl Into<String>,
    ) -> Self {
        Self {
            parts: Some(vec![Part::FunctionCall {
                function_call,
                thought_signature: Some(thought_signature.into()),
            }]),
            role: None,
        }
    }

    /// Create a new text content with thought signature
    pub fn text_with_thought_signature(
        text: impl Into<String>,
        thought_signature: impl Into<String>,
    ) -> Self {
        Self {
            parts: Some(vec![Part::Text {
                text: text.into(),
                thought: None,
                thought_signature: Some(thought_signature.into()),
            }]),
            role: None,
        }
    }

    /// Create a new thought content with thought signature
    pub fn thought_with_signature(
        text: impl Into<String>,
        thought_signature: impl Into<String>,
    ) -> Self {
        Self {
            parts: Some(vec![Part::Text {
                text: text.into(),
                thought: Some(true),
                thought_signature: Some(thought_signature.into()),
            }]),
            role: None,
        }
    }

    /// Create a new content with a function response
    pub fn function_response(function_response: super::tools::FunctionResponse) -> Self {
        Self {
            parts: Some(vec![Part::FunctionResponse {
                function_response,
                thought_signature: None,
            }]),
            role: None,
        }
    }

    /// Create a new content with a function response from name and JSON value
    pub fn function_response_json(name: impl Into<String>, response: serde_json::Value) -> Self {
        Self {
            parts: Some(vec![Part::FunctionResponse {
                function_response: super::tools::FunctionResponse::new(name, response),
                thought_signature: None,
            }]),
            role: None,
        }
    }

    /// Create a new content with inline data (blob data)
    pub fn inline_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
        Self {
            parts: Some(vec![Part::InlineData { inline_data: Blob::new(mime_type, data) }]),
            role: None,
        }
    }

    /// Create function response content with multimodal parts.
    ///
    /// The `FunctionResponse` carries its multimodal data (inline images, file references)
    /// in its own `parts` field, matching the Gemini wire format where `inlineData`/`fileData`
    /// entries are nested inside the `functionResponse` object.
    pub fn function_response_multimodal(function_response: super::tools::FunctionResponse) -> Self {
        Self {
            parts: Some(vec![Part::FunctionResponse {
                function_response,
                thought_signature: None,
            }]),
            role: None,
        }
    }

    /// Add a role to this content
    pub fn with_role(mut self, role: Role) -> Self {
        self.role = Some(role);
        self
    }
}

/// Message in a conversation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    /// Content of the message
    pub content: Content,
    /// Role of the message
    pub role: Role,
}

impl Message {
    /// Create a new user message with text content
    pub fn user(text: impl Into<String>) -> Self {
        Self { content: Content::text(text).with_role(Role::User), role: Role::User }
    }

    /// Create a new model message with text content
    pub fn model(text: impl Into<String>) -> Self {
        Self { content: Content::text(text).with_role(Role::Model), role: Role::Model }
    }

    /// Create a new embedding message with text content
    pub fn embed(text: impl Into<String>) -> Self {
        Self { content: Content::text(text), role: Role::Model }
    }

    /// Create a new function message with function response content from JSON
    pub fn function(name: impl Into<String>, response: serde_json::Value) -> Self {
        Self {
            content: Content::function_response_json(name, response).with_role(Role::Model),
            role: Role::Model,
        }
    }

    /// Create a new function message with function response from a JSON string
    pub fn function_str(
        name: impl Into<String>,
        response: impl Into<String>,
    ) -> Result<Self, serde_json::Error> {
        let response_str = response.into();
        let json = serde_json::from_str(&response_str)?;
        Ok(Self {
            content: Content::function_response_json(name, json).with_role(Role::Model),
            role: Role::Model,
        })
    }
}

/// Content modality type - specifies the format of model output
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Modality {
    /// Default value.
    ModalityUnspecified,
    /// Indicates the model should return text.
    Text,
    /// Indicates the model should return images.
    Image,
    /// Indicates the model should return audio.
    Audio,
    /// Indicates the model should return video.
    Video,
    /// Indicates document content (PDFs, etc.)
    Document,
    /// Unknown or future modality types
    Unknown,
}

impl Modality {
    fn from_wire_str(value: &str) -> Self {
        match value {
            "MODALITY_UNSPECIFIED" => Self::ModalityUnspecified,
            "TEXT" => Self::Text,
            "IMAGE" => Self::Image,
            "AUDIO" => Self::Audio,
            "VIDEO" => Self::Video,
            "DOCUMENT" => Self::Document,
            _ => Self::Unknown,
        }
    }

    fn from_wire_number(value: i64) -> Self {
        match value {
            0 => Self::ModalityUnspecified,
            1 => Self::Text,
            2 => Self::Image,
            3 => Self::Video,
            4 => Self::Audio,
            5 => Self::Document,
            _ => Self::Unknown,
        }
    }
}

impl<'de> Deserialize<'de> for Modality {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value {
            serde_json::Value::String(s) => Ok(Self::from_wire_str(&s)),
            serde_json::Value::Number(n) => n
                .as_i64()
                .map(Self::from_wire_number)
                .ok_or_else(|| de::Error::custom("modality must be an integer-compatible number")),
            _ => Err(de::Error::custom("modality must be a string or integer")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tool_call_deserialize_and_roundtrip() {
        let json = r#"{"toolCall": {"name": "google_search", "args": {"query": "rust lang"}}}"#;
        let part: Part = serde_json::from_str(json).expect("should deserialize toolCall");
        match &part {
            Part::ToolCall { tool_call, .. } => {
                assert_eq!(tool_call["name"], "google_search");
                assert_eq!(tool_call["args"]["query"], "rust lang");
            }
            other => panic!("expected Part::ToolCall, got {other:?}"),
        }
        // Round-trip
        let serialized = serde_json::to_string(&part).expect("should serialize");
        let deserialized: Part =
            serde_json::from_str(&serialized).expect("should deserialize again");
        assert_eq!(part, deserialized);
    }

    #[test]
    fn test_tool_response_deserialize_and_roundtrip() {
        let json = r#"{"toolResponse": {"name": "google_search", "output": {"results": []}}, "thoughtSignature": "sig_123"}"#;
        let part: Part = serde_json::from_str(json).expect("should deserialize toolResponse");
        match &part {
            Part::ToolResponse { tool_response, thought_signature } => {
                assert_eq!(tool_response["name"], "google_search");
                assert_eq!(tool_response["output"]["results"], serde_json::json!([]));
                assert_eq!(thought_signature.as_deref(), Some("sig_123"));
            }
            other => panic!("expected Part::ToolResponse, got {other:?}"),
        }
        // Round-trip
        let serialized = serde_json::to_string(&part).expect("should serialize");
        let deserialized: Part =
            serde_json::from_str(&serialized).expect("should deserialize again");
        assert_eq!(part, deserialized);
    }

    #[test]
    fn test_code_execution_parts_preserve_thought_signature() {
        let executable = serde_json::json!({
            "executableCode": { "language": "python", "code": "print(1)" },
            "thoughtSignature": "sig_exec"
        });
        let result = serde_json::json!({
            "codeExecutionResult": { "outcome": "OUTCOME_OK", "output": "1" },
            "thoughtSignature": "sig_result"
        });

        let executable_part: Part =
            serde_json::from_value(executable).expect("should deserialize executable code");
        let result_part: Part =
            serde_json::from_value(result).expect("should deserialize code execution result");

        match executable_part {
            Part::ExecutableCode { thought_signature, .. } => {
                assert_eq!(thought_signature.as_deref(), Some("sig_exec"));
            }
            other => panic!("expected Part::ExecutableCode, got {other:?}"),
        }

        match result_part {
            Part::CodeExecutionResult { thought_signature, .. } => {
                assert_eq!(thought_signature.as_deref(), Some("sig_result"));
            }
            other => panic!("expected Part::CodeExecutionResult, got {other:?}"),
        }
    }

    // ===== Multimodal function response tests =====

    #[test]
    fn test_file_data_ref_serde_round_trip() {
        let file_ref = FileDataRef {
            mime_type: "application/pdf".to_string(),
            file_uri: "gs://bucket/report.pdf".to_string(),
        };
        let json = serde_json::to_string(&file_ref).unwrap();
        assert!(json.contains("mimeType"));
        assert!(json.contains("fileUri"));
        let deserialized: FileDataRef = serde_json::from_str(&json).unwrap();
        assert_eq!(file_ref, deserialized);
    }

    #[test]
    fn test_part_file_data_serde_round_trip() {
        let part = Part::FileData {
            file_data: FileDataRef {
                mime_type: "image/jpeg".to_string(),
                file_uri: "https://example.com/img.jpg".to_string(),
            },
        };
        let json = serde_json::to_string(&part).unwrap();
        assert!(json.contains("fileData"));
        let deserialized: Part = serde_json::from_str(&json).unwrap();
        assert_eq!(part, deserialized);
    }

    #[test]
    fn test_function_response_new_backward_compat() {
        let fr =
            super::super::tools::FunctionResponse::new("tool", serde_json::json!({"ok": true}));
        let json = serde_json::to_string(&fr).unwrap();
        // Should only have name and response — no inline_data or file_data keys
        let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&json).unwrap();
        assert!(map.contains_key("name"));
        assert!(map.contains_key("response"));
        assert!(!map.contains_key("inline_data"));
        assert!(!map.contains_key("file_data"));
    }

    #[test]
    fn test_function_response_with_inline_data_constructor() {
        let blobs = vec![Blob::new("image/png", "base64data")];
        let fr = super::super::tools::FunctionResponse::with_inline_data(
            "chart",
            serde_json::json!({"status": "ok"}),
            blobs.clone(),
        );
        assert_eq!(fr.name, "chart");
        assert_eq!(fr.parts.len(), 1);
        assert!(matches!(
            &fr.parts[0],
            super::super::tools::FunctionResponsePart::InlineData { inline_data }
            if inline_data == &blobs[0]
        ));
    }

    #[test]
    fn test_function_response_with_file_data_constructor() {
        let files = vec![FileDataRef {
            mime_type: "application/pdf".to_string(),
            file_uri: "gs://b/f.pdf".to_string(),
        }];
        let fr = super::super::tools::FunctionResponse::with_file_data(
            "doc",
            serde_json::json!({"ok": true}),
            files.clone(),
        );
        assert_eq!(fr.name, "doc");
        assert_eq!(fr.parts.len(), 1);
        assert!(matches!(
            &fr.parts[0],
            super::super::tools::FunctionResponsePart::FileData { file_data }
            if file_data == &files[0]
        ));
    }

    #[test]
    fn test_function_response_inline_data_only_constructor() {
        let blobs = vec![Blob::new("audio/wav", "audiodata")];
        let fr =
            super::super::tools::FunctionResponse::inline_data_only("audio_tool", blobs.clone());
        assert_eq!(fr.name, "audio_tool");
        assert!(fr.response.is_none());
        assert_eq!(fr.parts.len(), 1);
    }

    #[test]
    fn test_content_function_response_multimodal_parts_nested() {
        use super::super::tools::FunctionResponsePart;
        let blobs = [Blob::new("image/png", "img1"), Blob::new("image/jpeg", "img2")];
        let files = [FileDataRef {
            mime_type: "application/pdf".to_string(),
            file_uri: "gs://b/f.pdf".to_string(),
        }];
        let mut fr_parts: Vec<FunctionResponsePart> = blobs
            .iter()
            .map(|b| FunctionResponsePart::InlineData { inline_data: b.clone() })
            .collect();
        fr_parts
            .extend(files.iter().map(|f| FunctionResponsePart::FileData { file_data: f.clone() }));
        let fr = super::super::tools::FunctionResponse {
            name: "tool".to_string(),
            response: Some(serde_json::json!({"ok": true})),
            parts: fr_parts,
        };
        let content = Content::function_response_multimodal(fr);
        let content_parts = content.parts.unwrap();
        // Single FunctionResponse part in the Content
        assert_eq!(content_parts.len(), 1);
        assert!(matches!(&content_parts[0], Part::FunctionResponse { .. }));
        // The multimodal data is nested inside the FunctionResponse
        if let Part::FunctionResponse { function_response, .. } = &content_parts[0] {
            // 2 inline + 1 file = 3 nested parts
            assert_eq!(function_response.parts.len(), 3);
        } else {
            panic!("expected FunctionResponse part");
        }
    }

    #[test]
    fn test_multimodal_function_response_wire_format() {
        // Verify the serialized JSON matches the Gemini API wire format:
        // The `parts` array with `inlineData` lives INSIDE the `functionResponse` object.
        use super::super::tools::FunctionResponsePart;
        let fr = super::super::tools::FunctionResponse {
            name: "get_image".to_string(),
            response: Some(serde_json::json!({"image_ref": {"$ref": "photo.jpg"}})),
            parts: vec![FunctionResponsePart::InlineData {
                inline_data: Blob::new("image/jpeg", "base64encodeddata"),
            }],
        };

        let part = Part::FunctionResponse { function_response: fr, thought_signature: None };
        let json = serde_json::to_value(&part).unwrap();

        // The functionResponse object should contain name, response, AND parts
        let fr_obj = &json["functionResponse"];
        assert_eq!(fr_obj["name"], "get_image");
        assert!(fr_obj["response"].is_object());
        assert!(fr_obj["parts"].is_array());
        assert_eq!(fr_obj["parts"].as_array().unwrap().len(), 1);

        // The nested part should have inlineData with mimeType and data
        let inline = &fr_obj["parts"][0]["inlineData"];
        assert_eq!(inline["mimeType"], "image/jpeg");
        assert_eq!(inline["data"], "base64encodeddata");
    }

    #[test]
    fn test_json_only_function_response_has_no_parts_key() {
        // When there are no multimodal parts, the `parts` key should be absent
        let fr = super::super::tools::FunctionResponse::new(
            "simple_tool",
            serde_json::json!({"result": "ok"}),
        );
        let part = Part::FunctionResponse { function_response: fr, thought_signature: None };
        let json = serde_json::to_string(&part).unwrap();
        // Should NOT contain "parts" key at all
        assert!(
            !json.contains(r#""parts""#),
            "JSON-only response should not have parts key: {json}"
        );
    }
}