feat/function-response-parts #1
@@ -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"
|
||||||
|
|||||||
134
examples/function-response-image.rs
Normal file
134
examples/function-response-image.rs
Normal 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())
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user