google_search_with_functions/
google_search_with_functions.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!("--- Meeting Scheduler Function Calling example ---");
17
18    // Define a meeting scheduler function that matches the curl example
19    let schedule_meeting = FunctionDeclaration::new(
20        "schedule_meeting",
21        "Schedules a meeting with specified attendees at a given time and date.",
22        FunctionParameters::object()
23            .with_property(
24                "attendees",
25                PropertyDetails::array(
26                    "List of people attending the meeting.",
27                    PropertyDetails::string("Attendee name"),
28                ),
29                true,
30            )
31            .with_property(
32                "date",
33                PropertyDetails::string("Date of the meeting (e.g., '2024-07-29')"),
34                true,
35            )
36            .with_property(
37                "time",
38                PropertyDetails::string("Time of the meeting (e.g., '15:00')"),
39                true,
40            )
41            .with_property(
42                "topic",
43                PropertyDetails::string("The subject or topic of the meeting."),
44                true,
45            ),
46    );
47
48    // Create function tool
49    let function_tool = Tool::new(schedule_meeting);
50
51    // Create a request with the tool - matching the curl example
52    let response = client
53        .generate_content()
54        .with_user_message("Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.")
55        .with_tool(function_tool.clone())
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, function_call.args
65        );
66
67        // Handle the schedule_meeting function
68        if function_call.name == "schedule_meeting" {
69            let attendees: Vec<String> = function_call.get("attendees")?;
70            let date: String = function_call.get("date")?;
71            let time: String = function_call.get("time")?;
72            let topic: String = function_call.get("topic")?;
73
74            println!("Scheduling meeting:");
75            println!("  Attendees: {:?}", attendees);
76            println!("  Date: {}", date);
77            println!("  Time: {}", time);
78            println!("  Topic: {}", topic);
79
80            // Simulate scheduling the meeting
81            let meeting_id = format!(
82                "meeting_{}",
83                std::time::SystemTime::now()
84                    .duration_since(std::time::UNIX_EPOCH)
85                    .unwrap()
86                    .as_secs()
87            );
88
89            let function_response = json!({
90                "success": true,
91                "meeting_id": meeting_id,
92                "message": format!("Meeting '{}' scheduled for {} at {} with {:?}", topic, date, time, attendees)
93            });
94
95            // Create conversation with function response
96            let mut conversation = client.generate_content();
97
98            // 1. Add original user message
99            conversation = conversation
100                .with_user_message("Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.");
101
102            // 2. Add model message with function call
103            let model_function_call =
104                FunctionCall::new("schedule_meeting", function_call.args.clone());
105            let model_content = Content::function_call(model_function_call).with_role(Role::Model);
106            let model_message = Message {
107                content: model_content,
108                role: Role::Model,
109            };
110            conversation = conversation.with_message(model_message);
111
112            // 3. Add function response
113            conversation =
114                conversation.with_function_response("schedule_meeting", function_response);
115
116            // Execute final request
117            let final_response = conversation.execute().await?;
118
119            println!("Final response: {}", final_response.text());
120        } else {
121            println!("Unknown function call: {}", function_call.name);
122        }
123    } else {
124        println!("No function calls in the response.");
125        println!("Direct response: {}", response.text());
126    }
127
128    Ok(())
129}