pub enum Tool {
Function {
function_declarations: Vec<FunctionDeclaration>,
},
GoogleSearch {
google_search: GoogleSearchConfig,
},
}
Expand description
Tool that can be used by the model
Variants§
Function
Function-based tool
Fields
§
function_declarations: Vec<FunctionDeclaration>
The function declaration for the tool
GoogleSearch
Google Search tool
Fields
§
google_search: GoogleSearchConfig
The Google Search configuration
Implementations§
Source§impl Tool
impl Tool
Sourcepub fn new(function_declaration: FunctionDeclaration) -> Self
pub fn new(function_declaration: FunctionDeclaration) -> Self
Create a new tool with a single function declaration
Examples found in repository?
examples/google_search_with_functions.rs (line 36)
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}
Sourcepub fn with_functions(function_declarations: Vec<FunctionDeclaration>) -> Self
pub fn with_functions(function_declarations: Vec<FunctionDeclaration>) -> Self
Create a new tool with multiple function declarations
Examples found in repository?
examples/tools.rs (line 53)
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 google_search() -> Self
pub fn google_search() -> Self
Create a new Google Search tool
Examples found in repository?
examples/google_search.rs (line 15)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 // Get API key from environment variable
7 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
8
9 // Create client
10 let client = Gemini::new(api_key);
11
12 println!("--- Google Search tool example ---");
13
14 // Create a Google Search tool
15 let google_search_tool = Tool::google_search();
16
17 // Create a request with Google Search tool
18 let response = client
19 .generate_content()
20 .with_user_message("What is the current Google stock price?")
21 .with_tool(google_search_tool)
22 .execute()
23 .await?;
24
25 println!("Response: {}", response.text());
26
27 Ok(())
28}
More examples
examples/curl_google_search.rs (line 43)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 // Get API key from environment variable
7 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
8
9 println!("--- Curl equivalent with Google Search tool ---");
10
11 // This is equivalent to the curl example:
12 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
13 // -H "Content-Type: application/json" \
14 // -d '{
15 // "contents": [
16 // {
17 // "parts": [
18 // {"text": "What is the current Google stock price?"}
19 // ]
20 // }
21 // ],
22 // "tools": [
23 // {
24 // "google_search": {}
25 // }
26 // ]
27 // }'
28
29 // Create client
30 let client = Gemini::new(api_key);
31
32 // Create a content part that matches the JSON in the curl example
33 let text_part = Part::Text {
34 text: "What is the current Google stock price?".to_string(),
35 };
36
37 let content = Content {
38 parts: vec![text_part],
39 role: None,
40 };
41
42 // Create a Google Search tool
43 let google_search_tool = Tool::google_search();
44
45 // Add the content and tool directly to the request
46 // This exactly mirrors the JSON structure in the curl example
47 let mut content_builder = client.generate_content();
48 content_builder.contents.push(content);
49 content_builder = content_builder.with_tool(google_search_tool);
50
51 let response = content_builder.execute().await?;
52
53 println!("Response: {}", response.text());
54
55 Ok(())
56}
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Tool
impl<'de> Deserialize<'de> for Tool
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 Tool
impl RefUnwindSafe for Tool
impl Send for Tool
impl Sync for Tool
impl Unpin for Tool
impl UnwindSafe for Tool
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