From e12078000615f7f94cfc3d236e82e91051ce8738 Mon Sep 17 00:00:00 2001 From: Andre Cipriani Bandarra Date: Sat, 17 Oct 2026 15:02:29 +0100 Subject: [PATCH] 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()) + } +}