From f4f275f2f9963cfd44c1ce45c0955f8cc5ca66e2 Mon Sep 17 00:00:00 2001 From: Andre Cipriani Bandarra Date: Sat, 17 Oct 2026 14:49:53 +0100 Subject: [PATCH 1/2] feat: support multimodal function response parts Adds an optional parts field to FunctionResponseData, serialized as functionResponse.parts with inlineData, so function responses can carry images. It is omitted when empty, so existing requests are unchanged. --- src/types/common.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/types/common.rs b/src/types/common.rs index 3c08ff5..6b2c17d 100644 --- a/src/types/common.rs +++ b/src/types/common.rs @@ -151,6 +151,7 @@ impl Part { function_response: Some(FunctionResponseData { name: name.into(), response, + parts: vec![], }), ..Default::default() } @@ -167,6 +168,16 @@ pub struct FunctionCallData { pub struct FunctionResponseData { pub name: String, pub response: Value, + /// Media returned by the function (multimodal function responses), sent as + /// `functionResponse.parts`. Omitted when empty. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub parts: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FunctionResponsePart { + pub inline_data: InlineData, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -182,3 +193,46 @@ pub struct FileData { pub mime_type: String, pub file_uri: String, } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::{FunctionResponsePart, InlineData, Part}; + + #[test] + fn function_response_omits_empty_parts() { + let part = Part::function_response("lookup", json!({"output": "ok"})); + assert_eq!( + serde_json::to_value(&part).unwrap(), + json!({"functionResponse": {"name": "lookup", "response": {"output": "ok"}}}) + ); + } + + #[test] + fn function_response_serializes_inline_data_parts() { + let mut part = Part::function_response("screenshot", json!({})); + part.function_response.as_mut().unwrap().parts = vec![FunctionResponsePart { + inline_data: InlineData { + mime_type: "image/png".to_string(), + data: "aGVsbG8=".to_string(), + }, + }]; + assert_eq!( + serde_json::to_value(&part).unwrap(), + json!({"functionResponse": { + "name": "screenshot", + "response": {}, + "parts": [{"inlineData": {"mimeType": "image/png", "data": "aGVsbG8="}}] + }}) + ); + } + + #[test] + fn function_response_without_parts_deserializes() { + let part: Part = + serde_json::from_value(json!({"functionResponse": {"name": "lookup", "response": {}}})) + .unwrap(); + assert!(part.function_response.unwrap().parts.is_empty()); + } +} -- 2.49.1 From e12078000615f7f94cfc3d236e82e91051ce8738 Mon Sep 17 00:00:00 2001 From: Andre Cipriani Bandarra Date: Sat, 17 Oct 2026 15:02:29 +0100 Subject: [PATCH 2/2] docs: add multimodal function response example Calls a function, returns a solid-color PNG as functionResponse.parts inlineData, and checks that the model names the color. COLOR picks the color; otherwise it is picked by time. --- Cargo.toml | 1 + examples/function-response-image.rs | 134 ++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 examples/function-response-image.rs diff --git a/Cargo.toml b/Cargo.toml index 8fe851b..4380be8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ tokio = { version = "1" } tokio-stream = "0.1.18" [dev-dependencies] +base64 = "0.23.1" console = "0.16.4" dialoguer = "0.12.0" image = "0.25.10" diff --git a/examples/function-response-image.rs b/examples/function-response-image.rs new file mode 100644 index 0000000..6721f2b --- /dev/null +++ b/examples/function-response-image.rs @@ -0,0 +1,134 @@ +//! Returns an image from a function call as a multimodal function response +//! (`functionResponse.parts` with `inlineData`) and asks the model what it sees. +//! +//! The image is a solid square in a color picked at random, so a correct answer +//! shows the model actually received the image. + +use std::io::Cursor; +use std::time::{SystemTime, UNIX_EPOCH}; + +use base64::Engine; +use gemini_rs::prelude::*; +use image::{ImageFormat, Rgb, RgbImage}; +use serde_json::json; + +const COLORS: [(&str, [u8; 3]); 4] = [ + ("red", [220, 20, 20]), + ("green", [20, 180, 20]), + ("blue", [20, 40, 220]), + ("yellow", [240, 220, 20]), +]; + +fn square_png(rgb: [u8; 3]) -> Result> { + let image = RgbImage::from_pixel(64, 64, Rgb(rgb)); + let mut bytes = Cursor::new(Vec::new()); + image.write_to(&mut bytes, ImageFormat::Png)?; + Ok(base64::engine::general_purpose::STANDARD.encode(bytes.into_inner())) +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let authentication_manager = gcp_auth::provider().await?; + let api_endpoint = std::env::var("API_ENDPOINT")?; + let project_id = std::env::var("PROJECT_ID")?; + let location_id = std::env::var("LOCATION_ID")?; + let model = std::env::var("MODEL").unwrap_or_else(|_| "gemini-3.8-flash".to_string()); + + let gemini = GeminiClient::new( + authentication_manager, + api_endpoint, + project_id, + location_id, + ); + + let tools = vec![Tools { + function_declarations: Some(vec![FunctionDeclaration { + name: "take_snapshot".to_string(), + description: "Takes a snapshot of the camera and returns it as an image.".to_string(), + parameters: json!({"type": "object", "properties": {}}), + }]), + ..Default::default() + }]; + let mut contents = vec![ + Content::builder() + .role(Role::User) + .add_text_part( + "Take a snapshot with the camera and tell me, in one word, the color it shows.", + ) + .build(), + ]; + + let first = gemini + .generate_content( + &GenerateContentRequest::builder() + .contents(contents.clone()) + .tools(tools.clone()) + .build(), + &model, + ) + .await?; + let model_turn = first.candidates[0] + .content + .clone() + .ok_or("first response has no content")?; + let call = model_turn + .parts + .iter() + .flatten() + .find(|p| p.function_call.is_some()) + .ok_or("model did not call take_snapshot")? + .clone(); + println!( + "Model called: {}", + call.function_call.as_ref().unwrap().name + ); + + // `COLOR` picks one explicitly; otherwise pick by time (in microseconds, since + // some platforms' clocks have 100ns resolution). + let (color, rgb) = match std::env::var("COLOR") { + Ok(name) => *COLORS + .iter() + .find(|(c, _)| *c == name) + .ok_or_else(|| format!("unknown COLOR {name}"))?, + Err(_) => { + let micros = SystemTime::now().duration_since(UNIX_EPOCH)?.as_micros(); + COLORS[(micros % COLORS.len() as u128) as usize] + } + }; + println!("Returning a {color} image"); + + let mut response = Part::function_response("take_snapshot", json!({"status": "ok"})); + response.thought_signature = call.thought_signature.clone(); + response.function_response.as_mut().unwrap().parts = vec![FunctionResponsePart { + inline_data: InlineData { + mime_type: "image/png".to_string(), + data: square_png(rgb)?, + }, + }]; + contents.push(model_turn); + contents.push( + Content::builder() + .role(Role::User) + .add_part(response) + .build(), + ); + + let second = gemini + .generate_content( + &GenerateContentRequest::builder() + .contents(contents) + .tools(tools) + .build(), + &model, + ) + .await?; + let answer = second.candidates[0].get_text().unwrap_or_default(); + println!("Model answered: {answer}"); + + if answer.to_lowercase().contains(color) { + println!("OK: the model saw the {color} image"); + Ok(()) + } else { + Err(format!("expected the answer to mention {color}").into()) + } +} -- 2.49.1