pub struct PropertyDetails {
pub property_type: String,
pub description: String,
pub enum_values: Option<Vec<String>>,
pub items: Option<Box<PropertyDetails>>,
}
Expand description
Details about a property
Fields§
§property_type: String
The type of the property
description: String
The description of the property
enum_values: Option<Vec<String>>
The enum values if the property is an enum
items: Option<Box<PropertyDetails>>
The items if the property is an array
Implementations§
Source§impl PropertyDetails
impl PropertyDetails
Sourcepub fn string(description: impl Into<String>) -> Self
pub fn string(description: impl Into<String>) -> Self
Create a new string property
Examples found in repository?
examples/advanced.rs (line 22)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10 let api_key = env::var("GEMINI_API_KEY")?;
11
12 // Create client
13 let client = Gemini::new(api_key);
14
15 // Define a weather function
16 let get_weather = FunctionDeclaration::new(
17 "get_weather",
18 "Get the current weather for a location",
19 FunctionParameters::object()
20 .with_property(
21 "location",
22 PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
23 true,
24 )
25 .with_property(
26 "unit",
27 PropertyDetails::enum_type("The unit of temperature", ["celsius", "fahrenheit"]),
28 false,
29 ),
30 );
31
32 // Create a request with function calling
33 println!("Sending function call request...");
34 let response = client
35 .generate_content()
36 .with_user_message("What's the weather like in Tokyo right now?")
37 .with_function(get_weather)
38 .with_function_calling_mode(FunctionCallingMode::Any)
39 .execute()
40 .await?;
41
42 // Check if there are function calls
43 if let Some(function_call) = response.function_calls().first() {
44 println!(
45 "Function call received: {} with args: {}",
46 function_call.name, function_call.args
47 );
48
49 // Get parameters from the function call
50 let location: String = function_call.get("location")?;
51 let unit = function_call
52 .get::<String>("unit")
53 .unwrap_or_else(|_| String::from("celsius"));
54
55 println!("Location: {}, Unit: {}", location, unit);
56
57 // Simulate function execution (in a real app, this would call a weather API)
58 // Create a JSON response object
59 let weather_response = serde_json::json!({
60 "temperature": 22,
61 "unit": unit,
62 "condition": "sunny",
63 "location": location
64 });
65
66 // Continue the conversation with the function result
67 // We need to replay the entire conversation with the function response
68 println!("Sending function response...");
69
70 // First, need to recreate the original prompt and the model's response
71 let mut final_request = client
72 .generate_content()
73 .with_user_message("What's the weather like in Tokyo right now?");
74
75 // Add the function call from the model's response
76 let mut call_content = Content::default();
77 call_content.parts.push(Part::FunctionCall {
78 function_call: (*function_call).clone(),
79 });
80 let call_content = call_content.with_role(Role::Model);
81 final_request.contents.push(call_content);
82
83 // Now add the function response using the JSON value
84 final_request = final_request.with_function_response("get_weather", weather_response);
85
86 // Execute the request
87 let final_response = final_request.execute().await?;
88
89 println!("Final response: {}", final_response.text());
90 } else {
91 println!("No function calls in the response.");
92 println!("Response text: {}", response.text());
93 }
94
95 Ok(())
96}
More examples
examples/simple.rs (line 42)
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 // Simple generation
17 println!("--- Simple generation ---");
18 let response = client
19 .generate_content()
20 .with_system_prompt("You are a helpful assistant.")
21 .with_user_message("Hello, can you tell me a joke about programming?")
22 .with_generation_config(GenerationConfig {
23 temperature: Some(0.7),
24 max_output_tokens: Some(100),
25 ..Default::default()
26 })
27 .execute()
28 .await?;
29
30 println!("Response: {}", response.text());
31
32 // Function calling example
33 println!("\n--- Function calling example ---");
34
35 // Define a weather function
36 let get_weather = FunctionDeclaration::new(
37 "get_weather",
38 "Get the current weather for a location",
39 FunctionParameters::object()
40 .with_property(
41 "location",
42 PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
43 true,
44 )
45 .with_property(
46 "unit",
47 PropertyDetails::enum_type("The unit of temperature", ["celsius", "fahrenheit"]),
48 false,
49 ),
50 );
51
52 // Create a request with function calling
53 let response = client
54 .generate_content()
55 .with_system_prompt("You are a helpful weather assistant.")
56 .with_user_message("What's the weather like in San Francisco right now?")
57 .with_function(get_weather)
58 .with_function_calling_mode(FunctionCallingMode::Any)
59 .execute()
60 .await?;
61
62 // Check if there are function calls
63 if let Some(function_call) = response.function_calls().first() {
64 println!(
65 "Function call: {} with args: {}",
66 function_call.name, function_call.args
67 );
68
69 // Get parameters from the function call
70 let location: String = function_call.get("location")?;
71 let unit = function_call
72 .get::<String>("unit")
73 .unwrap_or_else(|_| String::from("celsius"));
74
75 println!("Location: {}, Unit: {}", location, unit);
76
77 let model_function_call = FunctionCall::new(
78 "get_weather",
79 json!({
80 "location": location,
81 "unit": unit
82 }),
83 );
84
85 // Create model content with function call
86 let model_content = Content::function_call(model_function_call).with_role(Role::Model);
87
88 // Add as model message
89 let model_message = Message {
90 content: model_content,
91 role: Role::Model,
92 };
93
94 // Simulate function execution
95 let weather_response = format!(
96 "{{\"temperature\": 22, \"unit\": \"{}\", \"condition\": \"sunny\"}}",
97 unit
98 );
99
100 // Continue the conversation with the function result
101 let final_response = client
102 .generate_content()
103 .with_system_prompt("You are a helpful weather assistant.")
104 .with_user_message("What's the weather like in San Francisco right now?")
105 .with_message(model_message)
106 .with_function_response_str("get_weather", weather_response)?
107 .with_generation_config(GenerationConfig {
108 temperature: Some(0.7),
109 max_output_tokens: Some(100),
110 ..Default::default()
111 })
112 .execute()
113 .await?;
114
115 println!("Final response: {}", final_response.text());
116 } else {
117 println!("No function calls in the response.");
118 }
119
120 Ok(())
121}
examples/tools.rs (line 25)
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 message with function call
110 let model_function_call = FunctionCall::new(
111 "calculate",
112 json!({
113 "operation": operation,
114 "a": a,
115 "b": b
116 }),
117 );
118
119 // Create model content with function call
120 let model_content =
121 Content::function_call(model_function_call).with_role(Role::Model);
122
123 // Add as model message
124 let model_message = Message {
125 content: model_content,
126 role: Role::Model,
127 };
128 conversation = conversation.with_message(model_message);
129
130 // 3. Add user message with function response
131 conversation =
132 conversation.with_function_response_str("calculate", function_response)?;
133
134 // Execute the request
135 let final_response = conversation.execute().await?;
136
137 println!("Final response: {}", final_response.text());
138 }
139 "get_weather" => {
140 let location: String = function_call.get("location")?;
141 let unit = function_call
142 .get::<String>("unit")
143 .unwrap_or_else(|_| String::from("celsius"));
144
145 println!("Weather request for: {}, Unit: {}", location, unit);
146
147 let weather_response = json!({
148 "temperature": 22,
149 "unit": unit,
150 "condition": "sunny"
151 })
152 .to_string();
153
154 // Based on the curl example, we need to structure the conversation properly:
155 // 1. A user message with the original query
156 // 2. A model message containing the function call
157 // 3. A user message containing the function response
158
159 // Construct conversation following the exact curl pattern
160 let mut conversation = client.generate_content();
161
162 // 1. Add user message with original query and system prompt
163 conversation = conversation
164 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
165 .with_user_message("What's 42 times 12?");
166
167 // 2. Create model message with function call
168 let model_function_call = FunctionCall::new(
169 "get_weather",
170 json!({
171 "location": location,
172 "unit": unit
173 }),
174 );
175
176 // Create model content with function call
177 let model_content =
178 Content::function_call(model_function_call).with_role(Role::Model);
179
180 // Add as model message
181 let model_message = Message {
182 content: model_content,
183 role: Role::Model,
184 };
185 conversation = conversation.with_message(model_message);
186
187 // 3. Add user message with function response
188 conversation =
189 conversation.with_function_response_str("get_weather", weather_response)?;
190
191 // Execute the request
192 let final_response = conversation.execute().await?;
193
194 println!("Final response: {}", final_response.text());
195 }
196 _ => println!("Unknown function"),
197 }
198 } else {
199 println!("No function calls in the response.");
200 println!("Response: {}", response.text());
201 }
202
203 Ok(())
204}
Sourcepub fn number(description: impl Into<String>) -> Self
pub fn number(description: impl Into<String>) -> Self
Create a new number property
Examples found in repository?
examples/google_search_with_functions.rs (line 31)
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!("--- Google Search with Function Calling example ---");
17
18 // Define a calculator function
19 let calculate = FunctionDeclaration::new(
20 "calculate",
21 "Perform a calculation",
22 FunctionParameters::object()
23 .with_property(
24 "operation",
25 PropertyDetails::enum_type(
26 "The mathematical operation to perform",
27 ["add", "subtract", "multiply", "divide"],
28 ),
29 true,
30 )
31 .with_property("a", PropertyDetails::number("The first number"), true)
32 .with_property("b", PropertyDetails::number("The second number"), true),
33 );
34
35 // Create function tool
36 let function_tool = Tool::new(calculate);
37
38 // Create a request with both tools
39 let response = client
40 .generate_content()
41 .with_user_message("What is the current Google stock price multiplied by 2?")
42 .with_tool(function_tool.clone())
43 .with_function_calling_mode(FunctionCallingMode::Any)
44 .execute()
45 .await?;
46
47 // Check if there are function calls
48 if let Some(function_call) = response.function_calls().first() {
49 println!(
50 "Function call: {} with args: {}",
51 function_call.name, function_call.args
52 );
53
54 // Handle the calculate function
55 if function_call.name == "calculate" {
56 let operation: String = function_call.get("operation")?;
57 let a: f64 = function_call.get("a")?;
58 let b: f64 = function_call.get("b")?;
59
60 println!("Calculation: {} {} {}", a, operation, b);
61
62 let result = match operation.as_str() {
63 "add" => a + b,
64 "subtract" => a - b,
65 "multiply" => a * b,
66 "divide" => a / b,
67 _ => panic!("Unknown operation"),
68 };
69
70 let function_response = json!({
71 "result": result,
72 })
73 .to_string();
74
75 // Based on the curl example, we need to structure the conversation properly:
76 // 1. A user message with the original query
77 // 2. A model message containing the function call
78 // 3. A user message containing the function response
79
80 // Construct conversation following the exact curl pattern
81 let mut conversation = client.generate_content();
82
83 // 1. Add user message with original query
84 conversation = conversation
85 .with_user_message("What is the current Google stock price multiplied by 2?");
86
87 // 2. Create model message with function call
88 let model_function_call = FunctionCall::new(
89 "calculate",
90 json!({
91 "operation": operation,
92 "a": a,
93 "b": b
94 }),
95 );
96
97 // Create model content with function call
98 let model_content = Content::function_call(model_function_call).with_role(Role::Model);
99
100 // Add as model message
101 let model_message = Message {
102 content: model_content,
103 role: Role::Model,
104 };
105 conversation = conversation.with_message(model_message);
106
107 // 3. Add user message with function response
108 conversation =
109 conversation.with_function_response_str("calculate", function_response)?;
110
111 // Execute the request
112 let final_response = conversation.execute().await?;
113
114 println!("Final response: {}", final_response.text());
115 } else {
116 println!("Unknown function call: {}", function_call.name);
117 }
118 } else {
119 println!("No function calls in the response.");
120 println!("Direct response: {}", response.text());
121 }
122
123 Ok(())
124}
More examples
examples/tools.rs (line 48)
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 message with function call
110 let model_function_call = FunctionCall::new(
111 "calculate",
112 json!({
113 "operation": operation,
114 "a": a,
115 "b": b
116 }),
117 );
118
119 // Create model content with function call
120 let model_content =
121 Content::function_call(model_function_call).with_role(Role::Model);
122
123 // Add as model message
124 let model_message = Message {
125 content: model_content,
126 role: Role::Model,
127 };
128 conversation = conversation.with_message(model_message);
129
130 // 3. Add user message with function response
131 conversation =
132 conversation.with_function_response_str("calculate", function_response)?;
133
134 // Execute the request
135 let final_response = conversation.execute().await?;
136
137 println!("Final response: {}", final_response.text());
138 }
139 "get_weather" => {
140 let location: String = function_call.get("location")?;
141 let unit = function_call
142 .get::<String>("unit")
143 .unwrap_or_else(|_| String::from("celsius"));
144
145 println!("Weather request for: {}, Unit: {}", location, unit);
146
147 let weather_response = json!({
148 "temperature": 22,
149 "unit": unit,
150 "condition": "sunny"
151 })
152 .to_string();
153
154 // Based on the curl example, we need to structure the conversation properly:
155 // 1. A user message with the original query
156 // 2. A model message containing the function call
157 // 3. A user message containing the function response
158
159 // Construct conversation following the exact curl pattern
160 let mut conversation = client.generate_content();
161
162 // 1. Add user message with original query and system prompt
163 conversation = conversation
164 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
165 .with_user_message("What's 42 times 12?");
166
167 // 2. Create model message with function call
168 let model_function_call = FunctionCall::new(
169 "get_weather",
170 json!({
171 "location": location,
172 "unit": unit
173 }),
174 );
175
176 // Create model content with function call
177 let model_content =
178 Content::function_call(model_function_call).with_role(Role::Model);
179
180 // Add as model message
181 let model_message = Message {
182 content: model_content,
183 role: Role::Model,
184 };
185 conversation = conversation.with_message(model_message);
186
187 // 3. Add user message with function response
188 conversation =
189 conversation.with_function_response_str("get_weather", weather_response)?;
190
191 // Execute the request
192 let final_response = conversation.execute().await?;
193
194 println!("Final response: {}", final_response.text());
195 }
196 _ => println!("Unknown function"),
197 }
198 } else {
199 println!("No function calls in the response.");
200 println!("Response: {}", response.text());
201 }
202
203 Ok(())
204}
Sourcepub fn array(description: impl Into<String>, items: PropertyDetails) -> Self
pub fn array(description: impl Into<String>, items: PropertyDetails) -> Self
Create a new array property
Sourcepub fn enum_type(
description: impl Into<String>,
enum_values: impl IntoIterator<Item = impl Into<String>>,
) -> Self
pub fn enum_type( description: impl Into<String>, enum_values: impl IntoIterator<Item = impl Into<String>>, ) -> Self
Create a new enum property
Examples found in repository?
examples/advanced.rs (line 27)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10 let api_key = env::var("GEMINI_API_KEY")?;
11
12 // Create client
13 let client = Gemini::new(api_key);
14
15 // Define a weather function
16 let get_weather = FunctionDeclaration::new(
17 "get_weather",
18 "Get the current weather for a location",
19 FunctionParameters::object()
20 .with_property(
21 "location",
22 PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
23 true,
24 )
25 .with_property(
26 "unit",
27 PropertyDetails::enum_type("The unit of temperature", ["celsius", "fahrenheit"]),
28 false,
29 ),
30 );
31
32 // Create a request with function calling
33 println!("Sending function call request...");
34 let response = client
35 .generate_content()
36 .with_user_message("What's the weather like in Tokyo right now?")
37 .with_function(get_weather)
38 .with_function_calling_mode(FunctionCallingMode::Any)
39 .execute()
40 .await?;
41
42 // Check if there are function calls
43 if let Some(function_call) = response.function_calls().first() {
44 println!(
45 "Function call received: {} with args: {}",
46 function_call.name, function_call.args
47 );
48
49 // Get parameters from the function call
50 let location: String = function_call.get("location")?;
51 let unit = function_call
52 .get::<String>("unit")
53 .unwrap_or_else(|_| String::from("celsius"));
54
55 println!("Location: {}, Unit: {}", location, unit);
56
57 // Simulate function execution (in a real app, this would call a weather API)
58 // Create a JSON response object
59 let weather_response = serde_json::json!({
60 "temperature": 22,
61 "unit": unit,
62 "condition": "sunny",
63 "location": location
64 });
65
66 // Continue the conversation with the function result
67 // We need to replay the entire conversation with the function response
68 println!("Sending function response...");
69
70 // First, need to recreate the original prompt and the model's response
71 let mut final_request = client
72 .generate_content()
73 .with_user_message("What's the weather like in Tokyo right now?");
74
75 // Add the function call from the model's response
76 let mut call_content = Content::default();
77 call_content.parts.push(Part::FunctionCall {
78 function_call: (*function_call).clone(),
79 });
80 let call_content = call_content.with_role(Role::Model);
81 final_request.contents.push(call_content);
82
83 // Now add the function response using the JSON value
84 final_request = final_request.with_function_response("get_weather", weather_response);
85
86 // Execute the request
87 let final_response = final_request.execute().await?;
88
89 println!("Final response: {}", final_response.text());
90 } else {
91 println!("No function calls in the response.");
92 println!("Response text: {}", response.text());
93 }
94
95 Ok(())
96}
More examples
examples/simple.rs (line 47)
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 // Simple generation
17 println!("--- Simple generation ---");
18 let response = client
19 .generate_content()
20 .with_system_prompt("You are a helpful assistant.")
21 .with_user_message("Hello, can you tell me a joke about programming?")
22 .with_generation_config(GenerationConfig {
23 temperature: Some(0.7),
24 max_output_tokens: Some(100),
25 ..Default::default()
26 })
27 .execute()
28 .await?;
29
30 println!("Response: {}", response.text());
31
32 // Function calling example
33 println!("\n--- Function calling example ---");
34
35 // Define a weather function
36 let get_weather = FunctionDeclaration::new(
37 "get_weather",
38 "Get the current weather for a location",
39 FunctionParameters::object()
40 .with_property(
41 "location",
42 PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
43 true,
44 )
45 .with_property(
46 "unit",
47 PropertyDetails::enum_type("The unit of temperature", ["celsius", "fahrenheit"]),
48 false,
49 ),
50 );
51
52 // Create a request with function calling
53 let response = client
54 .generate_content()
55 .with_system_prompt("You are a helpful weather assistant.")
56 .with_user_message("What's the weather like in San Francisco right now?")
57 .with_function(get_weather)
58 .with_function_calling_mode(FunctionCallingMode::Any)
59 .execute()
60 .await?;
61
62 // Check if there are function calls
63 if let Some(function_call) = response.function_calls().first() {
64 println!(
65 "Function call: {} with args: {}",
66 function_call.name, function_call.args
67 );
68
69 // Get parameters from the function call
70 let location: String = function_call.get("location")?;
71 let unit = function_call
72 .get::<String>("unit")
73 .unwrap_or_else(|_| String::from("celsius"));
74
75 println!("Location: {}, Unit: {}", location, unit);
76
77 let model_function_call = FunctionCall::new(
78 "get_weather",
79 json!({
80 "location": location,
81 "unit": unit
82 }),
83 );
84
85 // Create model content with function call
86 let model_content = Content::function_call(model_function_call).with_role(Role::Model);
87
88 // Add as model message
89 let model_message = Message {
90 content: model_content,
91 role: Role::Model,
92 };
93
94 // Simulate function execution
95 let weather_response = format!(
96 "{{\"temperature\": 22, \"unit\": \"{}\", \"condition\": \"sunny\"}}",
97 unit
98 );
99
100 // Continue the conversation with the function result
101 let final_response = client
102 .generate_content()
103 .with_system_prompt("You are a helpful weather assistant.")
104 .with_user_message("What's the weather like in San Francisco right now?")
105 .with_message(model_message)
106 .with_function_response_str("get_weather", weather_response)?
107 .with_generation_config(GenerationConfig {
108 temperature: Some(0.7),
109 max_output_tokens: Some(100),
110 ..Default::default()
111 })
112 .execute()
113 .await?;
114
115 println!("Final response: {}", final_response.text());
116 } else {
117 println!("No function calls in the response.");
118 }
119
120 Ok(())
121}
examples/google_search_with_functions.rs (lines 25-28)
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!("--- Google Search with Function Calling example ---");
17
18 // Define a calculator function
19 let calculate = FunctionDeclaration::new(
20 "calculate",
21 "Perform a calculation",
22 FunctionParameters::object()
23 .with_property(
24 "operation",
25 PropertyDetails::enum_type(
26 "The mathematical operation to perform",
27 ["add", "subtract", "multiply", "divide"],
28 ),
29 true,
30 )
31 .with_property("a", PropertyDetails::number("The first number"), true)
32 .with_property("b", PropertyDetails::number("The second number"), true),
33 );
34
35 // Create function tool
36 let function_tool = Tool::new(calculate);
37
38 // Create a request with both tools
39 let response = client
40 .generate_content()
41 .with_user_message("What is the current Google stock price multiplied by 2?")
42 .with_tool(function_tool.clone())
43 .with_function_calling_mode(FunctionCallingMode::Any)
44 .execute()
45 .await?;
46
47 // Check if there are function calls
48 if let Some(function_call) = response.function_calls().first() {
49 println!(
50 "Function call: {} with args: {}",
51 function_call.name, function_call.args
52 );
53
54 // Handle the calculate function
55 if function_call.name == "calculate" {
56 let operation: String = function_call.get("operation")?;
57 let a: f64 = function_call.get("a")?;
58 let b: f64 = function_call.get("b")?;
59
60 println!("Calculation: {} {} {}", a, operation, b);
61
62 let result = match operation.as_str() {
63 "add" => a + b,
64 "subtract" => a - b,
65 "multiply" => a * b,
66 "divide" => a / b,
67 _ => panic!("Unknown operation"),
68 };
69
70 let function_response = json!({
71 "result": result,
72 })
73 .to_string();
74
75 // Based on the curl example, we need to structure the conversation properly:
76 // 1. A user message with the original query
77 // 2. A model message containing the function call
78 // 3. A user message containing the function response
79
80 // Construct conversation following the exact curl pattern
81 let mut conversation = client.generate_content();
82
83 // 1. Add user message with original query
84 conversation = conversation
85 .with_user_message("What is the current Google stock price multiplied by 2?");
86
87 // 2. Create model message with function call
88 let model_function_call = FunctionCall::new(
89 "calculate",
90 json!({
91 "operation": operation,
92 "a": a,
93 "b": b
94 }),
95 );
96
97 // Create model content with function call
98 let model_content = Content::function_call(model_function_call).with_role(Role::Model);
99
100 // Add as model message
101 let model_message = Message {
102 content: model_content,
103 role: Role::Model,
104 };
105 conversation = conversation.with_message(model_message);
106
107 // 3. Add user message with function response
108 conversation =
109 conversation.with_function_response_str("calculate", function_response)?;
110
111 // Execute the request
112 let final_response = conversation.execute().await?;
113
114 println!("Final response: {}", final_response.text());
115 } else {
116 println!("Unknown function call: {}", function_call.name);
117 }
118 } else {
119 println!("No function calls in the response.");
120 println!("Direct response: {}", response.text());
121 }
122
123 Ok(())
124}
examples/tools.rs (line 30)
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 message with function call
110 let model_function_call = FunctionCall::new(
111 "calculate",
112 json!({
113 "operation": operation,
114 "a": a,
115 "b": b
116 }),
117 );
118
119 // Create model content with function call
120 let model_content =
121 Content::function_call(model_function_call).with_role(Role::Model);
122
123 // Add as model message
124 let model_message = Message {
125 content: model_content,
126 role: Role::Model,
127 };
128 conversation = conversation.with_message(model_message);
129
130 // 3. Add user message with function response
131 conversation =
132 conversation.with_function_response_str("calculate", function_response)?;
133
134 // Execute the request
135 let final_response = conversation.execute().await?;
136
137 println!("Final response: {}", final_response.text());
138 }
139 "get_weather" => {
140 let location: String = function_call.get("location")?;
141 let unit = function_call
142 .get::<String>("unit")
143 .unwrap_or_else(|_| String::from("celsius"));
144
145 println!("Weather request for: {}, Unit: {}", location, unit);
146
147 let weather_response = json!({
148 "temperature": 22,
149 "unit": unit,
150 "condition": "sunny"
151 })
152 .to_string();
153
154 // Based on the curl example, we need to structure the conversation properly:
155 // 1. A user message with the original query
156 // 2. A model message containing the function call
157 // 3. A user message containing the function response
158
159 // Construct conversation following the exact curl pattern
160 let mut conversation = client.generate_content();
161
162 // 1. Add user message with original query and system prompt
163 conversation = conversation
164 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
165 .with_user_message("What's 42 times 12?");
166
167 // 2. Create model message with function call
168 let model_function_call = FunctionCall::new(
169 "get_weather",
170 json!({
171 "location": location,
172 "unit": unit
173 }),
174 );
175
176 // Create model content with function call
177 let model_content =
178 Content::function_call(model_function_call).with_role(Role::Model);
179
180 // Add as model message
181 let model_message = Message {
182 content: model_content,
183 role: Role::Model,
184 };
185 conversation = conversation.with_message(model_message);
186
187 // 3. Add user message with function response
188 conversation =
189 conversation.with_function_response_str("get_weather", weather_response)?;
190
191 // Execute the request
192 let final_response = conversation.execute().await?;
193
194 println!("Final response: {}", final_response.text());
195 }
196 _ => println!("Unknown function"),
197 }
198 } else {
199 println!("No function calls in the response.");
200 println!("Response: {}", response.text());
201 }
202
203 Ok(())
204}
Trait Implementations§
Source§impl Clone for PropertyDetails
impl Clone for PropertyDetails
Source§fn clone(&self) -> PropertyDetails
fn clone(&self) -> PropertyDetails
Returns a copy of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moreSource§impl Debug for PropertyDetails
impl Debug for PropertyDetails
Source§impl<'de> Deserialize<'de> for PropertyDetails
impl<'de> Deserialize<'de> for PropertyDetails
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
Auto Trait Implementations§
impl Freeze for PropertyDetails
impl RefUnwindSafe for PropertyDetails
impl Send for PropertyDetails
impl Sync for PropertyDetails
impl Unpin for PropertyDetails
impl UnwindSafe for PropertyDetails
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