Merge pull request 'feat/function-response-parts' (#1) from feat/function-response-parts into main
Some checks failed
Rust / build (push) Has been cancelled
Some checks failed
Rust / build (push) Has been cancelled
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
@@ -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())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user