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 45)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10 // Get API key from environment variable
11 let api_key = env::var("GOOGLE_API_KEY")
12 .expect("GOOGLE_API_KEY environment variable not set");
13
14 // Create client
15 let client = Gemini::new(api_key);
16
17 println!("--- Google Search with Function Calling example ---");
18
19 // Define a calculator function
20 let calculate = FunctionDeclaration::new(
21 "calculate",
22 "Perform a calculation",
23 FunctionParameters::object()
24 .with_property(
25 "operation",
26 PropertyDetails::enum_type(
27 "The mathematical operation to perform",
28 ["add", "subtract", "multiply", "divide"]
29 ),
30 true,
31 )
32 .with_property(
33 "a",
34 PropertyDetails::number("The first number"),
35 true,
36 )
37 .with_property(
38 "b",
39 PropertyDetails::number("The second number"),
40 true,
41 ),
42 );
43
44 // Create function tool
45 let function_tool = Tool::new(calculate);
46
47 // Create Google Search tool
48 let google_search_tool = Tool::google_search();
49
50 // Create a request with both tools
51 let response = client
52 .generate_content()
53 .with_user_message("What is the current Google stock price multiplied by 2?")
54 .with_tool(google_search_tool)
55 .with_tool(function_tool)
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,
65 function_call.args
66 );
67
68 // Handle the calculate function
69 if function_call.name == "calculate" {
70 let operation: String = function_call.get("operation")?;
71 let a: f64 = function_call.get("a")?;
72 let b: f64 = function_call.get("b")?;
73
74 println!("Calculation: {} {} {}", a, operation, b);
75
76 let result = match operation.as_str() {
77 "add" => a + b,
78 "subtract" => a - b,
79 "multiply" => a * b,
80 "divide" => a / b,
81 _ => panic!("Unknown operation"),
82 };
83
84 let function_response = json!({
85 "result": result,
86 }).to_string();
87
88 // Continue the conversation with the function result
89 let final_response = client
90 .generate_content()
91 .with_user_message("What is the current Google stock price multiplied by 2?")
92 .with_function_response_str("calculate", function_response)?
93 .execute()
94 .await?;
95
96 println!("Final response: {}", final_response.text());
97 } else {
98 println!("Unknown function call: {}", function_call.name);
99 }
100 } else {
101 println!("No function calls in the response.");
102 println!("Direct response: {}", response.text());
103 }
104
105 Ok(())
106}
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 65)
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")
12 .expect("GEMINI_API_KEY environment variable not set");
13
14 // Create client
15 let client = Gemini::new(api_key);
16
17 println!("--- Tools example with multiple functions ---");
18
19 // Define a weather function
20 let get_weather = FunctionDeclaration::new(
21 "get_weather",
22 "Get the current weather for a location",
23 FunctionParameters::object()
24 .with_property(
25 "location",
26 PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
27 true,
28 )
29 .with_property(
30 "unit",
31 PropertyDetails::enum_type(
32 "The unit of temperature",
33 ["celsius", "fahrenheit"]
34 ),
35 false,
36 ),
37 );
38
39 // Define a calculator function
40 let calculate = FunctionDeclaration::new(
41 "calculate",
42 "Perform a calculation",
43 FunctionParameters::object()
44 .with_property(
45 "operation",
46 PropertyDetails::enum_type(
47 "The mathematical operation to perform",
48 ["add", "subtract", "multiply", "divide"]
49 ),
50 true,
51 )
52 .with_property(
53 "a",
54 PropertyDetails::number("The first number"),
55 true,
56 )
57 .with_property(
58 "b",
59 PropertyDetails::number("The second number"),
60 true,
61 ),
62 );
63
64 // Create a tool with multiple functions
65 let tool = Tool::with_functions(vec![get_weather, calculate]);
66
67 // Create a request with tool functions
68 let response = client
69 .generate_content()
70 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
71 .with_user_message("What's 42 times 12?")
72 .with_tool(tool)
73 .with_function_calling_mode(FunctionCallingMode::Any)
74 .execute()
75 .await?;
76
77 // Process function calls
78 if let Some(function_call) = response.function_calls().first() {
79 println!(
80 "Function call: {} with args: {}",
81 function_call.name,
82 function_call.args
83 );
84
85 // Handle different function calls
86 match function_call.name.as_str() {
87 "calculate" => {
88 let operation: String = function_call.get("operation")?;
89 let a: f64 = function_call.get("a")?;
90 let b: f64 = function_call.get("b")?;
91
92 println!("Calculation: {} {} {}", a, operation, b);
93
94 let result = match operation.as_str() {
95 "add" => a + b,
96 "subtract" => a - b,
97 "multiply" => a * b,
98 "divide" => a / b,
99 _ => panic!("Unknown operation"),
100 };
101
102 let function_response = json!({
103 "result": result,
104 }).to_string();
105
106 // Continue the conversation with the function result
107 let final_response = client
108 .generate_content()
109 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
110 .with_user_message("What's 42 times 12?")
111 .with_function_response_str("calculate", function_response)?
112 .execute()
113 .await?;
114
115 println!("Final response: {}", final_response.text());
116 },
117 "get_weather" => {
118 let location: String = function_call.get("location")?;
119 let unit = function_call.get::<String>("unit").unwrap_or_else(|_| String::from("celsius"));
120
121 println!("Weather request for: {}, Unit: {}", location, unit);
122
123 let weather_response = json!({
124 "temperature": 22,
125 "unit": unit,
126 "condition": "sunny"
127 }).to_string();
128
129 // Continue the conversation with the function result
130 let final_response = client
131 .generate_content()
132 .with_system_prompt("You are a helpful assistant that can check weather and perform calculations.")
133 .with_user_message("What's 42 times 12?")
134 .with_function_response_str("get_weather", weather_response)?
135 .execute()
136 .await?;
137
138 println!("Final response: {}", final_response.text());
139 },
140 _ => println!("Unknown function"),
141 }
142 } else {
143 println!("No function calls in the response.");
144 println!("Response: {}", response.text());
145 }
146
147 Ok(())
148}
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 16)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 // Get API key from environment variable
7 let api_key = env::var("GOOGLE_API_KEY")
8 .expect("GOOGLE_API_KEY environment variable not set");
9
10 // Create client
11 let client = Gemini::new(api_key);
12
13 println!("--- Google Search tool example ---");
14
15 // Create a Google Search tool
16 let google_search_tool = Tool::google_search();
17
18 // Create a request with Google Search tool
19 let response = client
20 .generate_content()
21 .with_user_message("What is the current Google stock price?")
22 .with_tool(google_search_tool)
23 .execute()
24 .await?;
25
26 println!("Response: {}", response.text());
27
28 Ok(())
29}
More examples
examples/curl_google_search.rs (line 44)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 // Get API key from environment variable
7 let api_key = env::var("GOOGLE_API_KEY")
8 .expect("GOOGLE_API_KEY environment variable not set");
9
10 println!("--- Curl equivalent with Google Search tool ---");
11
12 // This is equivalent to the curl example:
13 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
14 // -H "Content-Type: application/json" \
15 // -d '{
16 // "contents": [
17 // {
18 // "parts": [
19 // {"text": "What is the current Google stock price?"}
20 // ]
21 // }
22 // ],
23 // "tools": [
24 // {
25 // "google_search": {}
26 // }
27 // ]
28 // }'
29
30 // Create client
31 let client = Gemini::new(api_key);
32
33 // Create a content part that matches the JSON in the curl example
34 let text_part = Part::Text {
35 text: "What is the current Google stock price?".to_string()
36 };
37
38 let content = Content {
39 parts: vec![text_part],
40 role: None,
41 };
42
43 // Create a Google Search tool
44 let google_search_tool = Tool::google_search();
45
46 // Add the content and tool directly to the request
47 // This exactly mirrors the JSON structure in the curl example
48 let mut content_builder = client.generate_content();
49 content_builder.contents.push(content);
50 content_builder = content_builder.with_tool(google_search_tool);
51
52 let response = content_builder.execute().await?;
53
54 println!("Response: {}", response.text());
55
56 Ok(())
57}
examples/google_search_with_functions.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("GOOGLE_API_KEY")
12 .expect("GOOGLE_API_KEY environment variable not set");
13
14 // Create client
15 let client = Gemini::new(api_key);
16
17 println!("--- Google Search with Function Calling example ---");
18
19 // Define a calculator function
20 let calculate = FunctionDeclaration::new(
21 "calculate",
22 "Perform a calculation",
23 FunctionParameters::object()
24 .with_property(
25 "operation",
26 PropertyDetails::enum_type(
27 "The mathematical operation to perform",
28 ["add", "subtract", "multiply", "divide"]
29 ),
30 true,
31 )
32 .with_property(
33 "a",
34 PropertyDetails::number("The first number"),
35 true,
36 )
37 .with_property(
38 "b",
39 PropertyDetails::number("The second number"),
40 true,
41 ),
42 );
43
44 // Create function tool
45 let function_tool = Tool::new(calculate);
46
47 // Create Google Search tool
48 let google_search_tool = Tool::google_search();
49
50 // Create a request with both tools
51 let response = client
52 .generate_content()
53 .with_user_message("What is the current Google stock price multiplied by 2?")
54 .with_tool(google_search_tool)
55 .with_tool(function_tool)
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,
65 function_call.args
66 );
67
68 // Handle the calculate function
69 if function_call.name == "calculate" {
70 let operation: String = function_call.get("operation")?;
71 let a: f64 = function_call.get("a")?;
72 let b: f64 = function_call.get("b")?;
73
74 println!("Calculation: {} {} {}", a, operation, b);
75
76 let result = match operation.as_str() {
77 "add" => a + b,
78 "subtract" => a - b,
79 "multiply" => a * b,
80 "divide" => a / b,
81 _ => panic!("Unknown operation"),
82 };
83
84 let function_response = json!({
85 "result": result,
86 }).to_string();
87
88 // Continue the conversation with the function result
89 let final_response = client
90 .generate_content()
91 .with_user_message("What is the current Google stock price multiplied by 2?")
92 .with_function_response_str("calculate", function_response)?
93 .execute()
94 .await?;
95
96 println!("Final response: {}", final_response.text());
97 } else {
98 println!("Unknown function call: {}", function_call.name);
99 }
100 } else {
101 println!("No function calls in the response.");
102 println!("Direct response: {}", response.text());
103 }
104
105 Ok(())
106}
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