function_calling/
function_calling.rs1use gemini_client_api::gemini::ask::Gemini;
2use gemini_client_api::gemini::types::request::Tool;
3use gemini_client_api::gemini::types::sessions::Session;
4use gemini_client_api::gemini::utils::{execute_function_calls, gemini_function, GeminiSchema};
5use std::env;
6use std::error::Error;
7
8#[gemini_function]
11fn add_numbers(
13 a: f64,
15 b: f64,
17) -> f64 {
18 println!("[Executing Tool] adding {} + {}", a, b);
19 a + b
20}
21
22#[gemini_function]
23fn get_temperature(location: String) -> String {
25 println!("[Executing Tool] getting temperature for {}", location);
26 format!("25°C in {}", location)
27}
28
29#[tokio::main]
30async fn main() -> Result<(), Box<dyn Error>> {
31 let mut session = Session::new(10);
32 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set");
33
34 let ai = Gemini::new(api_key, "gemini-2.5-flash", None)
36 .set_tools(vec![Tool::FunctionDeclarations(vec![
37 add_numbers::gemini_schema(),
38 get_temperature::gemini_schema(),
39 ])]);
40
41 println!("--- Function Calling Example ---");
42 let prompt = "What is 123.45 plus 678.9, and what's the weather like in London?";
43 println!("User: {}\n", prompt);
44
45 let mut response = ai.ask(session.ask_string(prompt)).await?;
47
48 loop {
50 if response.get_chat().has_function_call() {
51 println!("Gemini requested function calls...");
52
53 let results = execute_function_calls!(session, add_numbers, get_temperature);
55
56 for (idx, res) in results.iter().enumerate() {
57 if let Some(r) = res {
58 println!(" Call #{} result: {:?}", idx, r);
59 }
60 }
61
62 response = ai.ask(&mut session).await?;
64 } else {
65 println!("\nGemini: {}", response.get_chat().get_text_no_think(""));
67 break;
68 }
69 }
70
71 Ok(())
72}