tools/
tools.rs

1use gemini_rust::{
2    Content, FunctionCall, FunctionCallingMode, FunctionDeclaration, FunctionParameters, Gemini,
3    Message, PropertyDetails, Role, Tool,
4};
5use serde_json::json;
6use std::env;
7
8#[tokio::main]
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}