Skip to main content

adk_gemini/
models.rs

1//! # Core Gemini API Primitives
2//!
3//! This module contains the fundamental building blocks used across the Gemini API.
4//! These core data structures are shared by multiple modules and form the foundation
5//! for constructing requests and parsing responses.
6//!
7//! ## Core Types
8//!
9//! - [`Role`] - Represents the speaker in a conversation (User or Model)
10//! - [`Part`] - Content fragments that make up messages (text, images, function calls)
11//! - [`Blob`] - Binary data with MIME type for inline content
12//! - [`Content`] - Container for parts with optional role assignment
13//! - [`Message`] - Complete message with content and explicit role
14//! - [`Modality`] - Output format types (text, image, audio)
15//!
16//! ## Usage
17//!
18//! These types are typically used in combination with the domain-specific modules:
19//! - `generation` - For content generation requests and responses
20//! - `embedding` - For text embedding operations
21//! - `safety` - For content moderation settings
22//! - `tools` - For function calling capabilities
23//! - `batch` - For batch processing operations
24//! - `cache` - For content caching
25//! - `files` - For file management
26
27#![allow(clippy::enum_variant_names)]
28
29use serde::{Deserialize, Serialize, de};
30
31/// Role of a message in a conversation
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
33#[serde(rename_all = "lowercase")]
34pub enum Role {
35    /// Message from the user
36    User,
37    /// Message from the model
38    Model,
39}
40
41/// Content part that can be included in a message
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
43#[serde(untagged)]
44pub enum Part {
45    /// Text content
46    Text {
47        /// The text content
48        text: String,
49        /// Whether this is a thought summary (Gemini 2.5 series only)
50        #[serde(skip_serializing_if = "Option::is_none")]
51        thought: Option<bool>,
52        /// The thought signature (Gemini 2.5+ thinking models only).
53        /// Preserved from responses and echoed back in conversation history for Gemini 3.x thought signature support.
54        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
55        thought_signature: Option<String>,
56    },
57    /// Inline binary data (base64-encoded with MIME type).
58    InlineData {
59        /// The blob data
60        #[serde(rename = "inlineData")]
61        inline_data: Blob,
62        /// How a video in the blob is clipped and sampled.
63        #[serde(rename = "videoMetadata", default, skip_serializing_if = "Option::is_none")]
64        video_metadata: Option<VideoMetadata>,
65    },
66    /// File data referenced by URI
67    FileData {
68        /// The file data reference.
69        #[serde(rename = "fileData")]
70        file_data: FileDataRef,
71        /// How a video in the file is clipped and sampled.
72        #[serde(rename = "videoMetadata", default, skip_serializing_if = "Option::is_none")]
73        video_metadata: Option<VideoMetadata>,
74    },
75    /// Function call from the model
76    FunctionCall {
77        /// The function call details
78        #[serde(rename = "functionCall")]
79        function_call: super::tools::FunctionCall,
80        /// The thought signature (Gemini 2.5+ thinking models only).
81        /// Preserved from responses and echoed back in conversation history for Gemini 3.x thought signature support.
82        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
83        thought_signature: Option<String>,
84    },
85    /// Function response (results from executing a function call)
86    FunctionResponse {
87        /// The function response details
88        #[serde(rename = "functionResponse")]
89        function_response: super::tools::FunctionResponse,
90        /// The thought signature (Gemini 3.x thinking models).
91        /// Must be echoed back on function response parts when thinking is active.
92        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
93        thought_signature: Option<String>,
94    },
95    /// Server-side tool call from Gemini 3 (built-in tool invocation)
96    ToolCall {
97        /// The tool call payload.
98        #[serde(rename = "toolCall")]
99        tool_call: serde_json::Value,
100        /// The thought signature (Gemini 3.x thinking models).
101        /// Must be preserved and echoed back in conversation history.
102        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
103        thought_signature: Option<String>,
104    },
105    /// Server-side tool response from Gemini 3 (built-in tool result)
106    ToolResponse {
107        /// The tool response payload.
108        #[serde(rename = "toolResponse")]
109        tool_response: serde_json::Value,
110        /// The thought signature (Gemini 3.x thinking models).
111        /// Must be preserved and echoed back in conversation history.
112        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
113        thought_signature: Option<String>,
114    },
115    /// Generated code emitted by Gemini code execution.
116    ExecutableCode {
117        /// The executable code payload.
118        #[serde(rename = "executableCode")]
119        executable_code: serde_json::Value,
120        /// The thought signature (Gemini 3.x thinking models).
121        /// Must be preserved and echoed back in conversation history.
122        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
123        thought_signature: Option<String>,
124    },
125    /// Result emitted by Gemini code execution.
126    CodeExecutionResult {
127        /// The code execution result payload.
128        #[serde(rename = "codeExecutionResult")]
129        code_execution_result: serde_json::Value,
130        /// The thought signature (Gemini 3.x thinking models).
131        /// Must be preserved and echoed back in conversation history.
132        #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
133        thought_signature: Option<String>,
134    },
135}
136
137/// Blob for a message part
138#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
139#[serde(rename_all = "camelCase")]
140pub struct Blob {
141    /// The MIME type of the data
142    pub mime_type: String,
143    /// Base64 encoded data
144    pub data: String,
145}
146
147impl Blob {
148    /// Create a new blob with mime type and data
149    pub fn new(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
150        Self { mime_type: mime_type.into(), data: data.into() }
151    }
152}
153
154/// How Gemini clips and samples a video part: `videoMetadata` beside its `inlineData` or
155/// `fileData`.
156///
157/// Gemini samples video at 1 frame per second by default; `fps` sets another rate, and the
158/// offsets analyse only part of the clip.
159///
160/// # Example
161///
162/// ```rust
163/// use adk_gemini::VideoMetadata;
164///
165/// let metadata = VideoMetadata::default().with_fps(0.5).with_offsets(Some(30.0), Some(90.0));
166/// let json = serde_json::to_value(&metadata).unwrap();
167/// assert_eq!(json, serde_json::json!({"fps": 0.5, "startOffset": "30s", "endOffset": "90s"}));
168/// ```
169#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
170#[serde(rename_all = "camelCase")]
171pub struct VideoMetadata {
172    /// Frames per second to sample, in `(0.0, 24.0]`.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub fps: Option<f64>,
175    /// Where to start, as a duration such as `"30s"`.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub start_offset: Option<String>,
178    /// Where to end, as a duration such as `"90s"`.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub end_offset: Option<String>,
181}
182
183impl VideoMetadata {
184    /// Samples `fps` frames per second.
185    pub fn with_fps(mut self, fps: f64) -> Self {
186        self.fps = Some(fps);
187        self
188    }
189
190    /// Analyses from `start` to `end` seconds into the clip.
191    pub fn with_offsets(mut self, start: Option<f64>, end: Option<f64>) -> Self {
192        self.start_offset = start.map(|s| format!("{s}s"));
193        self.end_offset = end.map(|s| format!("{s}s"));
194        self
195    }
196}
197
198/// Reference to an external file by URI, used in Gemini wire format.
199///
200/// # Example
201///
202/// ```rust
203/// use adk_gemini::FileDataRef;
204///
205/// let file_ref = FileDataRef {
206///     mime_type: "application/pdf".to_string(),
207///     file_uri: "gs://my-bucket/report.pdf".to_string(),
208/// };
209/// ```
210#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
211#[serde(rename_all = "camelCase")]
212pub struct FileDataRef {
213    /// The MIME type of the referenced file.
214    pub mime_type: String,
215    /// The URI of the file (e.g. `gs://bucket/path` or a Gemini file URI).
216    pub file_uri: String,
217}
218
219/// Content of a message
220#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
221#[serde(rename_all = "camelCase")]
222pub struct Content {
223    /// Parts of the content
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub parts: Option<Vec<Part>>,
226    /// Role of the content
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub role: Option<Role>,
229}
230
231impl Content {
232    /// Create a new text content
233    pub fn text(text: impl Into<String>) -> Self {
234        Self {
235            parts: Some(vec![Part::Text {
236                text: text.into(),
237                thought: None,
238                thought_signature: None,
239            }]),
240            role: None,
241        }
242    }
243
244    /// Create a new content with a function call
245    pub fn function_call(function_call: super::tools::FunctionCall) -> Self {
246        Self {
247            parts: Some(vec![Part::FunctionCall { function_call, thought_signature: None }]),
248            role: None,
249        }
250    }
251
252    /// Create a new content with a function call and thought signature
253    pub fn function_call_with_thought(
254        function_call: super::tools::FunctionCall,
255        thought_signature: impl Into<String>,
256    ) -> Self {
257        Self {
258            parts: Some(vec![Part::FunctionCall {
259                function_call,
260                thought_signature: Some(thought_signature.into()),
261            }]),
262            role: None,
263        }
264    }
265
266    /// Create a new text content with thought signature
267    pub fn text_with_thought_signature(
268        text: impl Into<String>,
269        thought_signature: impl Into<String>,
270    ) -> Self {
271        Self {
272            parts: Some(vec![Part::Text {
273                text: text.into(),
274                thought: None,
275                thought_signature: Some(thought_signature.into()),
276            }]),
277            role: None,
278        }
279    }
280
281    /// Create a new thought content with thought signature
282    pub fn thought_with_signature(
283        text: impl Into<String>,
284        thought_signature: impl Into<String>,
285    ) -> Self {
286        Self {
287            parts: Some(vec![Part::Text {
288                text: text.into(),
289                thought: Some(true),
290                thought_signature: Some(thought_signature.into()),
291            }]),
292            role: None,
293        }
294    }
295
296    /// Create a new content with a function response
297    pub fn function_response(function_response: super::tools::FunctionResponse) -> Self {
298        Self {
299            parts: Some(vec![Part::FunctionResponse {
300                function_response,
301                thought_signature: None,
302            }]),
303            role: None,
304        }
305    }
306
307    /// Create a new content with a function response from name and JSON value
308    pub fn function_response_json(name: impl Into<String>, response: serde_json::Value) -> Self {
309        Self {
310            parts: Some(vec![Part::FunctionResponse {
311                function_response: super::tools::FunctionResponse::new(name, response),
312                thought_signature: None,
313            }]),
314            role: None,
315        }
316    }
317
318    /// Create a new content with inline data (blob data)
319    pub fn inline_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
320        Self {
321            parts: Some(vec![Part::InlineData {
322                inline_data: Blob::new(mime_type, data),
323                video_metadata: None,
324            }]),
325            role: None,
326        }
327    }
328
329    /// Create function response content with multimodal parts.
330    ///
331    /// The `FunctionResponse` carries its multimodal data (inline images, file references)
332    /// in its own `parts` field, matching the Gemini wire format where `inlineData`/`fileData`
333    /// entries are nested inside the `functionResponse` object.
334    pub fn function_response_multimodal(function_response: super::tools::FunctionResponse) -> Self {
335        Self {
336            parts: Some(vec![Part::FunctionResponse {
337                function_response,
338                thought_signature: None,
339            }]),
340            role: None,
341        }
342    }
343
344    /// Add a role to this content
345    pub fn with_role(mut self, role: Role) -> Self {
346        self.role = Some(role);
347        self
348    }
349}
350
351/// Message in a conversation
352#[derive(Debug, Clone, Serialize, Deserialize)]
353pub struct Message {
354    /// Content of the message
355    pub content: Content,
356    /// Role of the message
357    pub role: Role,
358}
359
360impl Message {
361    /// Create a new user message with text content
362    pub fn user(text: impl Into<String>) -> Self {
363        Self { content: Content::text(text).with_role(Role::User), role: Role::User }
364    }
365
366    /// Create a new model message with text content
367    pub fn model(text: impl Into<String>) -> Self {
368        Self { content: Content::text(text).with_role(Role::Model), role: Role::Model }
369    }
370
371    /// Create a new embedding message with text content
372    pub fn embed(text: impl Into<String>) -> Self {
373        Self { content: Content::text(text), role: Role::Model }
374    }
375
376    /// Create a new function message with function response content from JSON
377    pub fn function(name: impl Into<String>, response: serde_json::Value) -> Self {
378        Self {
379            content: Content::function_response_json(name, response).with_role(Role::Model),
380            role: Role::Model,
381        }
382    }
383
384    /// Create a new function message with function response from a JSON string
385    pub fn function_str(
386        name: impl Into<String>,
387        response: impl Into<String>,
388    ) -> Result<Self, serde_json::Error> {
389        let response_str = response.into();
390        let json = serde_json::from_str(&response_str)?;
391        Ok(Self {
392            content: Content::function_response_json(name, json).with_role(Role::Model),
393            role: Role::Model,
394        })
395    }
396}
397
398/// Content modality type - specifies the format of model output
399#[derive(Debug, Clone, Serialize, PartialEq)]
400#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
401pub enum Modality {
402    /// Default value.
403    ModalityUnspecified,
404    /// Indicates the model should return text.
405    Text,
406    /// Indicates the model should return images.
407    Image,
408    /// Indicates the model should return audio.
409    Audio,
410    /// Indicates the model should return video.
411    Video,
412    /// Indicates document content (PDFs, etc.)
413    Document,
414    /// Unknown or future modality types
415    Unknown,
416}
417
418impl Modality {
419    fn from_wire_str(value: &str) -> Self {
420        match value {
421            "MODALITY_UNSPECIFIED" => Self::ModalityUnspecified,
422            "TEXT" => Self::Text,
423            "IMAGE" => Self::Image,
424            "AUDIO" => Self::Audio,
425            "VIDEO" => Self::Video,
426            "DOCUMENT" => Self::Document,
427            _ => Self::Unknown,
428        }
429    }
430
431    fn from_wire_number(value: i64) -> Self {
432        match value {
433            0 => Self::ModalityUnspecified,
434            1 => Self::Text,
435            2 => Self::Image,
436            3 => Self::Video,
437            4 => Self::Audio,
438            5 => Self::Document,
439            _ => Self::Unknown,
440        }
441    }
442}
443
444impl<'de> Deserialize<'de> for Modality {
445    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
446    where
447        D: serde::Deserializer<'de>,
448    {
449        let value = serde_json::Value::deserialize(deserializer)?;
450        match value {
451            serde_json::Value::String(s) => Ok(Self::from_wire_str(&s)),
452            serde_json::Value::Number(n) => n
453                .as_i64()
454                .map(Self::from_wire_number)
455                .ok_or_else(|| de::Error::custom("modality must be an integer-compatible number")),
456            _ => Err(de::Error::custom("modality must be a string or integer")),
457        }
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    #[test]
466    fn test_tool_call_deserialize_and_roundtrip() {
467        let json = r#"{"toolCall": {"name": "google_search", "args": {"query": "rust lang"}}}"#;
468        let part: Part = serde_json::from_str(json).expect("should deserialize toolCall");
469        match &part {
470            Part::ToolCall { tool_call, .. } => {
471                assert_eq!(tool_call["name"], "google_search");
472                assert_eq!(tool_call["args"]["query"], "rust lang");
473            }
474            other => panic!("expected Part::ToolCall, got {other:?}"),
475        }
476        // Round-trip
477        let serialized = serde_json::to_string(&part).expect("should serialize");
478        let deserialized: Part =
479            serde_json::from_str(&serialized).expect("should deserialize again");
480        assert_eq!(part, deserialized);
481    }
482
483    #[test]
484    fn test_tool_response_deserialize_and_roundtrip() {
485        let json = r#"{"toolResponse": {"name": "google_search", "output": {"results": []}}, "thoughtSignature": "sig_123"}"#;
486        let part: Part = serde_json::from_str(json).expect("should deserialize toolResponse");
487        match &part {
488            Part::ToolResponse { tool_response, thought_signature } => {
489                assert_eq!(tool_response["name"], "google_search");
490                assert_eq!(tool_response["output"]["results"], serde_json::json!([]));
491                assert_eq!(thought_signature.as_deref(), Some("sig_123"));
492            }
493            other => panic!("expected Part::ToolResponse, got {other:?}"),
494        }
495        // Round-trip
496        let serialized = serde_json::to_string(&part).expect("should serialize");
497        let deserialized: Part =
498            serde_json::from_str(&serialized).expect("should deserialize again");
499        assert_eq!(part, deserialized);
500    }
501
502    #[test]
503    fn test_code_execution_parts_preserve_thought_signature() {
504        let executable = serde_json::json!({
505            "executableCode": { "language": "python", "code": "print(1)" },
506            "thoughtSignature": "sig_exec"
507        });
508        let result = serde_json::json!({
509            "codeExecutionResult": { "outcome": "OUTCOME_OK", "output": "1" },
510            "thoughtSignature": "sig_result"
511        });
512
513        let executable_part: Part =
514            serde_json::from_value(executable).expect("should deserialize executable code");
515        let result_part: Part =
516            serde_json::from_value(result).expect("should deserialize code execution result");
517
518        match executable_part {
519            Part::ExecutableCode { thought_signature, .. } => {
520                assert_eq!(thought_signature.as_deref(), Some("sig_exec"));
521            }
522            other => panic!("expected Part::ExecutableCode, got {other:?}"),
523        }
524
525        match result_part {
526            Part::CodeExecutionResult { thought_signature, .. } => {
527                assert_eq!(thought_signature.as_deref(), Some("sig_result"));
528            }
529            other => panic!("expected Part::CodeExecutionResult, got {other:?}"),
530        }
531    }
532
533    // ===== Multimodal function response tests =====
534
535    #[test]
536    fn test_file_data_ref_serde_round_trip() {
537        let file_ref = FileDataRef {
538            mime_type: "application/pdf".to_string(),
539            file_uri: "gs://bucket/report.pdf".to_string(),
540        };
541        let json = serde_json::to_string(&file_ref).unwrap();
542        assert!(json.contains("mimeType"));
543        assert!(json.contains("fileUri"));
544        let deserialized: FileDataRef = serde_json::from_str(&json).unwrap();
545        assert_eq!(file_ref, deserialized);
546    }
547
548    #[test]
549    fn test_part_file_data_serde_round_trip() {
550        let part = Part::FileData {
551            file_data: FileDataRef {
552                mime_type: "image/jpeg".to_string(),
553                file_uri: "https://example.com/img.jpg".to_string(),
554            },
555            video_metadata: None,
556        };
557        let json = serde_json::to_string(&part).unwrap();
558        assert!(json.contains("fileData"));
559        assert!(!json.contains("videoMetadata"));
560        let deserialized: Part = serde_json::from_str(&json).unwrap();
561        assert_eq!(part, deserialized);
562    }
563
564    #[test]
565    fn video_metadata_sits_beside_the_file_data() {
566        let part = Part::FileData {
567            file_data: FileDataRef {
568                mime_type: "video/mp4".to_string(),
569                file_uri: "https://generativelanguage.googleapis.com/v1beta/files/abc".to_string(),
570            },
571            video_metadata: Some(VideoMetadata::default().with_fps(1.0)),
572        };
573        let json = serde_json::to_value(&part).unwrap();
574        assert_eq!(
575            json,
576            serde_json::json!({
577                "fileData": {
578                    "mimeType": "video/mp4",
579                    "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/abc"
580                },
581                "videoMetadata": {"fps": 1.0}
582            })
583        );
584        assert_eq!(serde_json::from_value::<Part>(json).unwrap(), part);
585    }
586
587    #[test]
588    fn test_function_response_new_backward_compat() {
589        let fr =
590            super::super::tools::FunctionResponse::new("tool", serde_json::json!({"ok": true}));
591        let json = serde_json::to_string(&fr).unwrap();
592        // Should only have name and response — no inline_data or file_data keys
593        let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&json).unwrap();
594        assert!(map.contains_key("name"));
595        assert!(map.contains_key("response"));
596        assert!(!map.contains_key("inline_data"));
597        assert!(!map.contains_key("file_data"));
598    }
599
600    #[test]
601    fn test_function_response_with_inline_data_constructor() {
602        let blobs = vec![Blob::new("image/png", "base64data")];
603        let fr = super::super::tools::FunctionResponse::with_inline_data(
604            "chart",
605            serde_json::json!({"status": "ok"}),
606            blobs.clone(),
607        );
608        assert_eq!(fr.name, "chart");
609        assert_eq!(fr.parts.len(), 1);
610        assert!(matches!(
611            &fr.parts[0],
612            super::super::tools::FunctionResponsePart::InlineData { inline_data }
613            if inline_data == &blobs[0]
614        ));
615    }
616
617    #[test]
618    fn test_function_response_with_file_data_constructor() {
619        let files = vec![FileDataRef {
620            mime_type: "application/pdf".to_string(),
621            file_uri: "gs://b/f.pdf".to_string(),
622        }];
623        let fr = super::super::tools::FunctionResponse::with_file_data(
624            "doc",
625            serde_json::json!({"ok": true}),
626            files.clone(),
627        );
628        assert_eq!(fr.name, "doc");
629        assert_eq!(fr.parts.len(), 1);
630        assert!(matches!(
631            &fr.parts[0],
632            super::super::tools::FunctionResponsePart::FileData { file_data }
633            if file_data == &files[0]
634        ));
635    }
636
637    #[test]
638    fn test_function_response_inline_data_only_constructor() {
639        let blobs = vec![Blob::new("audio/wav", "audiodata")];
640        let fr =
641            super::super::tools::FunctionResponse::inline_data_only("audio_tool", blobs.clone());
642        assert_eq!(fr.name, "audio_tool");
643        assert!(fr.response.is_none());
644        assert_eq!(fr.parts.len(), 1);
645    }
646
647    #[test]
648    fn test_content_function_response_multimodal_parts_nested() {
649        use super::super::tools::FunctionResponsePart;
650        let blobs = [Blob::new("image/png", "img1"), Blob::new("image/jpeg", "img2")];
651        let files = [FileDataRef {
652            mime_type: "application/pdf".to_string(),
653            file_uri: "gs://b/f.pdf".to_string(),
654        }];
655        let mut fr_parts: Vec<FunctionResponsePart> = blobs
656            .iter()
657            .map(|b| FunctionResponsePart::InlineData { inline_data: b.clone() })
658            .collect();
659        fr_parts
660            .extend(files.iter().map(|f| FunctionResponsePart::FileData { file_data: f.clone() }));
661        let fr = super::super::tools::FunctionResponse {
662            name: "tool".to_string(),
663            id: None,
664            response: Some(serde_json::json!({"ok": true})),
665            parts: fr_parts,
666        };
667        let content = Content::function_response_multimodal(fr);
668        let content_parts = content.parts.unwrap();
669        // Single FunctionResponse part in the Content
670        assert_eq!(content_parts.len(), 1);
671        assert!(matches!(&content_parts[0], Part::FunctionResponse { .. }));
672        // The multimodal data is nested inside the FunctionResponse
673        if let Part::FunctionResponse { function_response, .. } = &content_parts[0] {
674            // 2 inline + 1 file = 3 nested parts
675            assert_eq!(function_response.parts.len(), 3);
676        } else {
677            panic!("expected FunctionResponse part");
678        }
679    }
680
681    #[test]
682    fn test_multimodal_function_response_wire_format() {
683        // Verify the serialized JSON matches the Gemini API wire format:
684        // The `parts` array with `inlineData` lives INSIDE the `functionResponse` object.
685        use super::super::tools::FunctionResponsePart;
686        let fr = super::super::tools::FunctionResponse {
687            name: "get_image".to_string(),
688            id: None,
689            response: Some(serde_json::json!({"image_ref": {"$ref": "photo.jpg"}})),
690            parts: vec![FunctionResponsePart::InlineData {
691                inline_data: Blob::new("image/jpeg", "base64encodeddata"),
692            }],
693        };
694
695        let part = Part::FunctionResponse { function_response: fr, thought_signature: None };
696        let json = serde_json::to_value(&part).unwrap();
697
698        // The functionResponse object should contain name, response, AND parts
699        let fr_obj = &json["functionResponse"];
700        assert_eq!(fr_obj["name"], "get_image");
701        assert!(fr_obj["response"].is_object());
702        assert!(fr_obj["parts"].is_array());
703        assert_eq!(fr_obj["parts"].as_array().unwrap().len(), 1);
704
705        // The nested part should have inlineData with mimeType and data
706        let inline = &fr_obj["parts"][0]["inlineData"];
707        assert_eq!(inline["mimeType"], "image/jpeg");
708        assert_eq!(inline["data"], "base64encodeddata");
709    }
710
711    #[test]
712    fn test_json_only_function_response_has_no_parts_key() {
713        // When there are no multimodal parts, the `parts` key should be absent
714        let fr = super::super::tools::FunctionResponse::new(
715            "simple_tool",
716            serde_json::json!({"result": "ok"}),
717        );
718        let part = Part::FunctionResponse { function_response: fr, thought_signature: None };
719        let json = serde_json::to_string(&part).unwrap();
720        // Should NOT contain "parts" key at all
721        assert!(
722            !json.contains(r#""parts""#),
723            "JSON-only response should not have parts key: {json}"
724        );
725    }
726}