2 Commits

Author SHA1 Message Date
e120780006 docs: add multimodal function response example
Some checks failed
Rust / build (pull_request) Has been cancelled
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.
2026-10-17 15:02:29 +01:00
f4f275f2f9 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.
2026-10-17 14:49:53 +01:00
3 changed files with 189 additions and 0 deletions

View File

@@ -18,6 +18,7 @@ tokio = { version = "1" }
tokio-stream = "0.1.18" tokio-stream = "0.1.18"
[dev-dependencies] [dev-dependencies]
base64 = "0.23.1"
console = "0.16.4" console = "0.16.4"
dialoguer = "0.12.0" dialoguer = "0.12.0"
image = "0.25.10" image = "0.25.10"

View File

@@ -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<String, Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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())
}
}

View File

@@ -151,6 +151,7 @@ impl Part {
function_response: Some(FunctionResponseData { function_response: Some(FunctionResponseData {
name: name.into(), name: name.into(),
response, response,
parts: vec![],
}), }),
..Default::default() ..Default::default()
} }
@@ -167,6 +168,16 @@ pub struct FunctionCallData {
pub struct FunctionResponseData { pub struct FunctionResponseData {
pub name: String, pub name: String,
pub response: Value, 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<FunctionResponsePart>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FunctionResponsePart {
pub inline_data: InlineData,
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
@@ -182,3 +193,46 @@ pub struct FileData {
pub mime_type: String, pub mime_type: String,
pub file_uri: 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());
}
}