pub struct Content {
pub parts: Option<Vec<Part>>,
pub role: Option<Role>,
}
Expand description
Content of a message
Fields§
§parts: Option<Vec<Part>>
Parts of the content
role: Option<Role>
Role of the content
Implementations§
Source§impl Content
impl Content
Sourcepub fn function_call(function_call: FunctionCall) -> Self
pub fn function_call(function_call: FunctionCall) -> Self
Create a new content with a function call
Examples found in repository?
examples/simple.rs (line 76)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9 // Get API key from environment variable
10 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
11
12 // Create client
13 let client = Gemini::new(api_key);
14
15 // Simple generation
16 println!("--- Simple generation ---");
17 let response = client
18 .generate_content()
19 .with_user_message("Hello, can you tell me a joke about programming?")
20 .with_generation_config(GenerationConfig {
21 temperature: Some(0.7),
22 max_output_tokens: Some(1000),
23 ..Default::default()
24 })
25 .execute()
26 .await?;
27
28 println!("Response: {}", response.text());
29
30 // Function calling example
31 println!("\n--- Function calling example ---");
32
33 // Define a weather function
34 let get_weather = FunctionDeclaration::new(
35 "get_weather",
36 "Get the current weather for a location",
37 FunctionParameters::object()
38 .with_property(
39 "location",
40 PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
41 true,
42 )
43 .with_property(
44 "unit",
45 PropertyDetails::enum_type("The unit of temperature", ["celsius", "fahrenheit"]),
46 false,
47 ),
48 );
49
50 // Create a request with function calling
51 let response = client
52 .generate_content()
53 .with_system_prompt("You are a helpful weather assistant.")
54 .with_user_message("What's the weather like in San Francisco right now?")
55 .with_function(get_weather)
56 .with_function_calling_mode(FunctionCallingMode::Any)
57 .execute()
58 .await?;
59
60 // Check if there are function calls
61 if let Some(function_call) = response.function_calls().first() {
62 println!(
63 "Function call: {} with args: {}",
64 function_call.name, function_call.args
65 );
66
67 // Get parameters from the function call
68 let location: String = function_call.get("location")?;
69 let unit = function_call
70 .get::<String>("unit")
71 .unwrap_or_else(|_| String::from("celsius"));
72
73 println!("Location: {}, Unit: {}", location, unit);
74
75 // Create model content with function call
76 let model_content = Content::function_call((*function_call).clone());
77
78 // Add as model message
79 let model_message = Message {
80 content: model_content,
81 role: Role::Model,
82 };
83
84 // Simulate function execution
85 let weather_response = format!(
86 "{{\"temperature\": 22, \"unit\": \"{}\", \"condition\": \"sunny\"}}",
87 unit
88 );
89
90 // Continue the conversation with the function result
91 let final_response = client
92 .generate_content()
93 .with_system_prompt("You are a helpful weather assistant.")
94 .with_user_message("What's the weather like in San Francisco right now?")
95 .with_message(model_message)
96 .with_function_response_str("get_weather", weather_response)?
97 .with_generation_config(GenerationConfig {
98 temperature: Some(0.7),
99 max_output_tokens: Some(100),
100 ..Default::default()
101 })
102 .execute()
103 .await?;
104
105 println!("Final response: {}", final_response.text());
106 } else {
107 println!("No function calls in the response.");
108 }
109
110 Ok(())
111}
More examples
examples/google_search_with_functions.rs (line 105)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10 // Get API key from environment variable
11 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
12
13 // Create client
14 let client = Gemini::new(api_key);
15
16 println!("--- Meeting Scheduler Function Calling example ---");
17
18 // Define a meeting scheduler function that matches the curl example
19 let schedule_meeting = FunctionDeclaration::new(
20 "schedule_meeting",
21 "Schedules a meeting with specified attendees at a given time and date.",
22 FunctionParameters::object()
23 .with_property(
24 "attendees",
25 PropertyDetails::array(
26 "List of people attending the meeting.",
27 PropertyDetails::string("Attendee name"),
28 ),
29 true,
30 )
31 .with_property(
32 "date",
33 PropertyDetails::string("Date of the meeting (e.g., '2024-07-29')"),
34 true,
35 )
36 .with_property(
37 "time",
38 PropertyDetails::string("Time of the meeting (e.g., '15:00')"),
39 true,
40 )
41 .with_property(
42 "topic",
43 PropertyDetails::string("The subject or topic of the meeting."),
44 true,
45 ),
46 );
47
48 // Create function tool
49 let function_tool = Tool::new(schedule_meeting);
50
51 // Create a request with the tool - matching the curl example
52 let response = client
53 .generate_content()
54 .with_user_message("Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.")
55 .with_tool(function_tool.clone())
56 .with_function_calling_mode(FunctionCallingMode::Any)
57 .execute()
58 .await?;
59
60 // Check if there are function calls
61 if let Some(function_call) = response.function_calls().first() {
62 println!(
63 "Function call: {} with args: {}",
64 function_call.name, function_call.args
65 );
66
67 // Handle the schedule_meeting function
68 if function_call.name == "schedule_meeting" {
69 let attendees: Vec<String> = function_call.get("attendees")?;
70 let date: String = function_call.get("date")?;
71 let time: String = function_call.get("time")?;
72 let topic: String = function_call.get("topic")?;
73
74 println!("Scheduling meeting:");
75 println!(" Attendees: {:?}", attendees);
76 println!(" Date: {}", date);
77 println!(" Time: {}", time);
78 println!(" Topic: {}", topic);
79
80 // Simulate scheduling the meeting
81 let meeting_id = format!(
82 "meeting_{}",
83 std::time::SystemTime::now()
84 .duration_since(std::time::UNIX_EPOCH)
85 .unwrap()
86 .as_secs()
87 );
88
89 let function_response = json!({
90 "success": true,
91 "meeting_id": meeting_id,
92 "message": format!("Meeting '{}' scheduled for {} at {} with {:?}", topic, date, time, attendees)
93 });
94
95 // Create conversation with function response
96 let mut conversation = client.generate_content();
97
98 // 1. Add original user message
99 conversation = conversation
100 .with_user_message("Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.");
101
102 // 2. Add model message with function call
103 let model_function_call =
104 FunctionCall::new("schedule_meeting", function_call.args.clone());
105 let model_content = Content::function_call(model_function_call).with_role(Role::Model);
106 let model_message = Message {
107 content: model_content,
108 role: Role::Model,
109 };
110 conversation = conversation.with_message(model_message);
111
112 // 3. Add function response
113 conversation =
114 conversation.with_function_response("schedule_meeting", function_response);
115
116 // Execute final request
117 let final_response = conversation.execute().await?;
118
119 println!("Final response: {}", final_response.text());
120 } else {
121 println!("Unknown function call: {}", function_call.name);
122 }
123 } else {
124 println!("No function calls in the response.");
125 println!("Direct response: {}", response.text());
126 }
127
128 Ok(())
129}
examples/tools.rs (line 110)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10 // Get API key from environment variable
11 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
12
13 // Create client
14 let client = Gemini::new(api_key);
15
16 println!("--- Tools example with multiple functions ---");
17
18 // Define a weather function
19 let get_weather = FunctionDeclaration::new(
20 "get_weather",
21 "Get the current weather for a location",
22 FunctionParameters::object()
23 .with_property(
24 "location",
25 PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
26 true,
27 )
28 .with_property(
29 "unit",
30 PropertyDetails::enum_type("The unit of temperature", ["celsius", "fahrenheit"]),
31 false,
32 ),
33 );
34
35 // Define a calculator function
36 let calculate = FunctionDeclaration::new(
37 "calculate",
38 "Perform a calculation",
39 FunctionParameters::object()
40 .with_property(
41 "operation",
42 PropertyDetails::enum_type(
43 "The mathematical operation to perform",
44 ["add", "subtract", "multiply", "divide"],
45 ),
46 true,
47 )
48 .with_property("a", PropertyDetails::number("The first number"), true)
49 .with_property("b", PropertyDetails::number("The second number"), true),
50 );
51
52 // Create a tool with multiple functions
53 let tool = Tool::with_functions(vec![get_weather, calculate]);
54
55 // Create a request with tool functions
56 let response = client
57 .generate_content()
58 .with_system_prompt(
59 "You are a helpful assistant that can check weather and perform calculations.",
60 )
61 .with_user_message("What's 42 times 12?")
62 .with_tool(tool)
63 .with_function_calling_mode(FunctionCallingMode::Any)
64 .execute()
65 .await?;
66
67 // Process function calls
68 if let Some(function_call) = response.function_calls().first() {
69 println!(
70 "Function call: {} with args: {}",
71 function_call.name, function_call.args
72 );
73
74 // Handle different function calls
75 match function_call.name.as_str() {
76 "calculate" => {
77 let operation: String = function_call.get("operation")?;
78 let a: f64 = function_call.get("a")?;
79 let b: f64 = function_call.get("b")?;
80
81 println!("Calculation: {} {} {}", a, operation, b);
82
83 let result = match operation.as_str() {
84 "add" => a + b,
85 "subtract" => a - b,
86 "multiply" => a * b,
87 "divide" => a / b,
88 _ => panic!("Unknown operation"),
89 };
90
91 let function_response = json!({
92 "result": result,
93 })
94 .to_string();
95
96 // Based on the curl example, we need to structure the conversation properly:
97 // 1. A user message with the original query
98 // 2. A model message containing the function call
99 // 3. A user message containing the function response
100
101 // Construct conversation following the exact curl pattern
102 let mut conversation = client.generate_content();
103
104 // 1. Add user message with original query and system prompt
105 conversation = conversation
106 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
107 .with_user_message("What's 42 times 12?");
108
109 // 2. Create model content with function call
110 let model_content = Content::function_call((*function_call).clone());
111
112 // Add as model message
113 let model_message = Message {
114 content: model_content,
115 role: Role::Model,
116 };
117 conversation = conversation.with_message(model_message);
118
119 // 3. Add user message with function response
120 conversation =
121 conversation.with_function_response_str("calculate", function_response)?;
122
123 // Execute the request
124 let final_response = conversation.execute().await?;
125
126 println!("Final response: {}", final_response.text());
127 }
128 "get_weather" => {
129 let location: String = function_call.get("location")?;
130 let unit = function_call
131 .get::<String>("unit")
132 .unwrap_or_else(|_| String::from("celsius"));
133
134 println!("Weather request for: {}, Unit: {}", location, unit);
135
136 let weather_response = json!({
137 "temperature": 22,
138 "unit": unit,
139 "condition": "sunny"
140 })
141 .to_string();
142
143 // Based on the curl example, we need to structure the conversation properly:
144 // 1. A user message with the original query
145 // 2. A model message containing the function call
146 // 3. A user message containing the function response
147
148 // Construct conversation following the exact curl pattern
149 let mut conversation = client.generate_content();
150
151 // 1. Add user message with original query and system prompt
152 conversation = conversation
153 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
154 .with_user_message("What's 42 times 12?");
155
156 // 2. Create model content with function call
157 let model_content = Content::function_call((*function_call).clone());
158
159 // Add as model message
160 let model_message = Message {
161 content: model_content,
162 role: Role::Model,
163 };
164 conversation = conversation.with_message(model_message);
165
166 // 3. Add user message with function response
167 conversation =
168 conversation.with_function_response_str("get_weather", weather_response)?;
169
170 // Execute the request
171 let final_response = conversation.execute().await?;
172
173 println!("Final response: {}", final_response.text());
174 }
175 _ => println!("Unknown function"),
176 }
177 } else {
178 println!("No function calls in the response.");
179 println!("Response: {}", response.text());
180 }
181
182 Ok(())
183}
Sourcepub fn function_response(function_response: FunctionResponse) -> Self
pub fn function_response(function_response: FunctionResponse) -> Self
Create a new content with a function response
Sourcepub fn function_response_json(name: impl Into<String>, response: Value) -> Self
pub fn function_response_json(name: impl Into<String>, response: Value) -> Self
Create a new content with a function response from name and JSON value
Sourcepub fn inline_data(
mime_type: impl Into<String>,
data: impl Into<String>,
) -> Self
pub fn inline_data( mime_type: impl Into<String>, data: impl Into<String>, ) -> Self
Create a new content with inline data (blob data)
Examples found in repository?
examples/mp4_describe.rs (line 23)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 // Read mp4 video file
13 let mut file = File::open("examples/sample.mp4")?;
14 let mut buffer = Vec::new();
15 file.read_to_end(&mut buffer)?;
16 let b64 = general_purpose::STANDARD.encode(&buffer);
17
18 // Get API key
19 let api_key = env::var("GEMINI_API_KEY")?;
20 let gemini = Gemini::pro(api_key);
21
22 // Example 1: Add mp4 blob using Message struct
23 let video_content = Content::inline_data("video/mp4", b64.clone());
24 let response1 = gemini
25 .generate_content()
26 .with_user_message("Please describe the content of this video (Message example)")
27 .with_message(gemini_rust::Message {
28 content: video_content,
29 role: gemini_rust::Role::User,
30 })
31 .execute()
32 .await?;
33
34 println!("AI description (Message): {}", response1.text());
35
36 // Example 2: Add mp4 blob directly using builder's with_inline_data
37 let response2 = gemini
38 .generate_content()
39 .with_user_message("Please describe the content of this video (with_inline_data example)")
40 .with_inline_data(b64, "video/mp4")
41 .execute()
42 .await?;
43
44 println!("AI description (with_inline_data): {}", response2.text());
45 Ok(())
46}
Sourcepub fn with_role(self, role: Role) -> Self
pub fn with_role(self, role: Role) -> Self
Add a role to this content
Examples found in repository?
examples/google_search_with_functions.rs (line 105)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10 // Get API key from environment variable
11 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
12
13 // Create client
14 let client = Gemini::new(api_key);
15
16 println!("--- Meeting Scheduler Function Calling example ---");
17
18 // Define a meeting scheduler function that matches the curl example
19 let schedule_meeting = FunctionDeclaration::new(
20 "schedule_meeting",
21 "Schedules a meeting with specified attendees at a given time and date.",
22 FunctionParameters::object()
23 .with_property(
24 "attendees",
25 PropertyDetails::array(
26 "List of people attending the meeting.",
27 PropertyDetails::string("Attendee name"),
28 ),
29 true,
30 )
31 .with_property(
32 "date",
33 PropertyDetails::string("Date of the meeting (e.g., '2024-07-29')"),
34 true,
35 )
36 .with_property(
37 "time",
38 PropertyDetails::string("Time of the meeting (e.g., '15:00')"),
39 true,
40 )
41 .with_property(
42 "topic",
43 PropertyDetails::string("The subject or topic of the meeting."),
44 true,
45 ),
46 );
47
48 // Create function tool
49 let function_tool = Tool::new(schedule_meeting);
50
51 // Create a request with the tool - matching the curl example
52 let response = client
53 .generate_content()
54 .with_user_message("Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.")
55 .with_tool(function_tool.clone())
56 .with_function_calling_mode(FunctionCallingMode::Any)
57 .execute()
58 .await?;
59
60 // Check if there are function calls
61 if let Some(function_call) = response.function_calls().first() {
62 println!(
63 "Function call: {} with args: {}",
64 function_call.name, function_call.args
65 );
66
67 // Handle the schedule_meeting function
68 if function_call.name == "schedule_meeting" {
69 let attendees: Vec<String> = function_call.get("attendees")?;
70 let date: String = function_call.get("date")?;
71 let time: String = function_call.get("time")?;
72 let topic: String = function_call.get("topic")?;
73
74 println!("Scheduling meeting:");
75 println!(" Attendees: {:?}", attendees);
76 println!(" Date: {}", date);
77 println!(" Time: {}", time);
78 println!(" Topic: {}", topic);
79
80 // Simulate scheduling the meeting
81 let meeting_id = format!(
82 "meeting_{}",
83 std::time::SystemTime::now()
84 .duration_since(std::time::UNIX_EPOCH)
85 .unwrap()
86 .as_secs()
87 );
88
89 let function_response = json!({
90 "success": true,
91 "meeting_id": meeting_id,
92 "message": format!("Meeting '{}' scheduled for {} at {} with {:?}", topic, date, time, attendees)
93 });
94
95 // Create conversation with function response
96 let mut conversation = client.generate_content();
97
98 // 1. Add original user message
99 conversation = conversation
100 .with_user_message("Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.");
101
102 // 2. Add model message with function call
103 let model_function_call =
104 FunctionCall::new("schedule_meeting", function_call.args.clone());
105 let model_content = Content::function_call(model_function_call).with_role(Role::Model);
106 let model_message = Message {
107 content: model_content,
108 role: Role::Model,
109 };
110 conversation = conversation.with_message(model_message);
111
112 // 3. Add function response
113 conversation =
114 conversation.with_function_response("schedule_meeting", function_response);
115
116 // Execute final request
117 let final_response = conversation.execute().await?;
118
119 println!("Final response: {}", final_response.text());
120 } else {
121 println!("Unknown function call: {}", function_call.name);
122 }
123 } else {
124 println!("No function calls in the response.");
125 println!("Direct response: {}", response.text());
126 }
127
128 Ok(())
129}
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Content
impl<'de> Deserialize<'de> for Content
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
impl StructuralPartialEq for Content
Auto Trait Implementations§
impl Freeze for Content
impl RefUnwindSafe for Content
impl Send for Content
impl Sync for Content
impl Unpin for Content
impl UnwindSafe for Content
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more