1#![allow(clippy::enum_variant_names)]
28
29use serde::{Deserialize, Serialize, de};
30
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
33#[serde(rename_all = "lowercase")]
34pub enum Role {
35 User,
37 Model,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
43#[serde(untagged)]
44pub enum Part {
45 Text {
47 text: String,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 thought: Option<bool>,
52 #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
55 thought_signature: Option<String>,
56 },
57 InlineData {
59 #[serde(rename = "inlineData")]
61 inline_data: Blob,
62 #[serde(rename = "videoMetadata", default, skip_serializing_if = "Option::is_none")]
64 video_metadata: Option<VideoMetadata>,
65 },
66 FileData {
68 #[serde(rename = "fileData")]
70 file_data: FileDataRef,
71 #[serde(rename = "videoMetadata", default, skip_serializing_if = "Option::is_none")]
73 video_metadata: Option<VideoMetadata>,
74 },
75 FunctionCall {
77 #[serde(rename = "functionCall")]
79 function_call: super::tools::FunctionCall,
80 #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
83 thought_signature: Option<String>,
84 },
85 FunctionResponse {
87 #[serde(rename = "functionResponse")]
89 function_response: super::tools::FunctionResponse,
90 #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
93 thought_signature: Option<String>,
94 },
95 ToolCall {
97 #[serde(rename = "toolCall")]
99 tool_call: serde_json::Value,
100 #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
103 thought_signature: Option<String>,
104 },
105 ToolResponse {
107 #[serde(rename = "toolResponse")]
109 tool_response: serde_json::Value,
110 #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
113 thought_signature: Option<String>,
114 },
115 ExecutableCode {
117 #[serde(rename = "executableCode")]
119 executable_code: serde_json::Value,
120 #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
123 thought_signature: Option<String>,
124 },
125 CodeExecutionResult {
127 #[serde(rename = "codeExecutionResult")]
129 code_execution_result: serde_json::Value,
130 #[serde(rename = "thoughtSignature", default, skip_serializing_if = "Option::is_none")]
133 thought_signature: Option<String>,
134 },
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
139#[serde(rename_all = "camelCase")]
140pub struct Blob {
141 pub mime_type: String,
143 pub data: String,
145}
146
147impl Blob {
148 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#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
170#[serde(rename_all = "camelCase")]
171pub struct VideoMetadata {
172 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub fps: Option<f64>,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub start_offset: Option<String>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub end_offset: Option<String>,
181}
182
183impl VideoMetadata {
184 pub fn with_fps(mut self, fps: f64) -> Self {
186 self.fps = Some(fps);
187 self
188 }
189
190 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
211#[serde(rename_all = "camelCase")]
212pub struct FileDataRef {
213 pub mime_type: String,
215 pub file_uri: String,
217}
218
219#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
221#[serde(rename_all = "camelCase")]
222pub struct Content {
223 #[serde(skip_serializing_if = "Option::is_none")]
225 pub parts: Option<Vec<Part>>,
226 #[serde(skip_serializing_if = "Option::is_none")]
228 pub role: Option<Role>,
229}
230
231impl Content {
232 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 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 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 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 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 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 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 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 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 pub fn with_role(mut self, role: Role) -> Self {
346 self.role = Some(role);
347 self
348 }
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize)]
353pub struct Message {
354 pub content: Content,
356 pub role: Role,
358}
359
360impl Message {
361 pub fn user(text: impl Into<String>) -> Self {
363 Self { content: Content::text(text).with_role(Role::User), role: Role::User }
364 }
365
366 pub fn model(text: impl Into<String>) -> Self {
368 Self { content: Content::text(text).with_role(Role::Model), role: Role::Model }
369 }
370
371 pub fn embed(text: impl Into<String>) -> Self {
373 Self { content: Content::text(text), role: Role::Model }
374 }
375
376 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 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#[derive(Debug, Clone, Serialize, PartialEq)]
400#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
401pub enum Modality {
402 ModalityUnspecified,
404 Text,
406 Image,
408 Audio,
410 Video,
412 Document,
414 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 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 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 #[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 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 assert_eq!(content_parts.len(), 1);
671 assert!(matches!(&content_parts[0], Part::FunctionResponse { .. }));
672 if let Part::FunctionResponse { function_response, .. } = &content_parts[0] {
674 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 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 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 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 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 assert!(
722 !json.contains(r#""parts""#),
723 "JSON-only response should not have parts key: {json}"
724 );
725 }
726}