Struct PropertyDetails

Source
pub struct PropertyDetails {
    pub property_type: String,
    pub description: String,
    pub enum_values: Option<Vec<String>>,
    pub items: Option<Box<PropertyDetails>>,
}
Expand description

Details about a property

Fields§

§property_type: String

The type of the property

§description: String

The description of the property

§enum_values: Option<Vec<String>>

The enum values if the property is an enum

§items: Option<Box<PropertyDetails>>

The items if the property is an array

Implementations§

Source§

impl PropertyDetails

Source

pub fn string(description: impl Into<String>) -> Self

Create a new string property

Examples found in repository?
examples/advanced.rs (line 22)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let api_key = env::var("GEMINI_API_KEY")?;
11    
12    // Create client
13    let client = Gemini::new(api_key);
14    
15    // Define a weather function
16    let get_weather = FunctionDeclaration::new(
17        "get_weather",
18        "Get the current weather for a location",
19        FunctionParameters::object()
20            .with_property(
21                "location",
22                PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
23                true,
24            )
25            .with_property(
26                "unit",
27                PropertyDetails::enum_type(
28                    "The unit of temperature", 
29                    ["celsius", "fahrenheit"]
30                ),
31                false,
32            ),
33    );
34
35    // Create a request with function calling
36    println!("Sending function call request...");
37    let response = client
38        .generate_content()
39        .with_user_message("What's the weather like in Tokyo right now?")
40        .with_function(get_weather)
41        .with_function_calling_mode(FunctionCallingMode::Any)
42        .execute()
43        .await?;
44
45    // Check if there are function calls
46    if let Some(function_call) = response.function_calls().first() {
47        println!(
48            "Function call received: {} with args: {}",
49            function_call.name,
50            function_call.args
51        );
52
53        // Get parameters from the function call
54        let location: String = function_call.get("location")?;
55        let unit = function_call.get::<String>("unit").unwrap_or_else(|_| String::from("celsius"));
56        
57        println!("Location: {}, Unit: {}", location, unit);
58        
59        // Simulate function execution (in a real app, this would call a weather API)
60        // Create a JSON response object
61        let weather_response = serde_json::json!({
62            "temperature": 22,
63            "unit": unit,
64            "condition": "sunny",
65            "location": location
66        });
67
68        // Continue the conversation with the function result
69        // We need to replay the entire conversation with the function response
70        println!("Sending function response...");
71        
72        // First, need to recreate the original prompt and the model's response
73        let mut final_request = client.generate_content()
74            .with_user_message("What's the weather like in Tokyo right now?");
75        
76        // Add the function call from the model's response
77        let mut call_content = Content::default();
78        call_content.parts.push(Part::FunctionCall { 
79            function_call: (*function_call).clone()
80        });
81        let call_content = call_content.with_role(Role::Model);
82        final_request.contents.push(call_content);
83        
84        // Now add the function response using the JSON value
85        final_request = final_request.with_function_response("get_weather", weather_response);
86        
87        // Execute the request
88        let final_response = final_request.execute().await?;
89
90        println!("Final response: {}", final_response.text());
91    } else {
92        println!("No function calls in the response.");
93        println!("Response text: {}", response.text());
94    }
95
96    Ok(())
97}
More examples
Hide additional examples
examples/simple.rs (line 44)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    // Get API key from environment variable
10    let api_key = env::var("GEMINI_API_KEY")
11        .expect("GEMINI_API_KEY environment variable not set");
12
13    // Create client
14    let client = Gemini::new(api_key);
15
16    // Simple generation
17    println!("--- Simple generation ---");
18    let response = client
19        .generate_content()
20        .with_system_prompt("You are a helpful assistant.")
21        .with_user_message("Hello, can you tell me a joke about programming?")
22        .with_generation_config(
23            GenerationConfig {
24                temperature: Some(0.7),
25                max_output_tokens: Some(100),
26                ..Default::default()
27            }
28        )
29        .execute()
30        .await?;
31
32    println!("Response: {}", response.text());
33
34    // Function calling example
35    println!("\n--- Function calling example ---");
36    
37    // Define a weather function
38    let get_weather = FunctionDeclaration::new(
39        "get_weather",
40        "Get the current weather for a location",
41        FunctionParameters::object()
42            .with_property(
43                "location",
44                PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
45                true,
46            )
47            .with_property(
48                "unit",
49                PropertyDetails::enum_type(
50                    "The unit of temperature", 
51                    ["celsius", "fahrenheit"]
52                ),
53                false,
54            ),
55    );
56
57    // Create a request with function calling
58    let response = client
59        .generate_content()
60        .with_system_prompt("You are a helpful weather assistant.")
61        .with_user_message("What's the weather like in San Francisco right now?")
62        .with_function(get_weather)
63        .with_function_calling_mode(FunctionCallingMode::Any)
64        .execute()
65        .await?;
66
67    // Check if there are function calls
68    if let Some(function_call) = response.function_calls().first() {
69        println!(
70            "Function call: {} with args: {}",
71            function_call.name,
72            function_call.args
73        );
74
75        // Get parameters from the function call
76        let location: String = function_call.get("location")?;
77        let unit = function_call.get::<String>("unit").unwrap_or_else(|_| String::from("celsius"));
78        
79        println!("Location: {}, Unit: {}", location, unit);
80        
81        // Simulate function execution
82        let weather_response = format!(
83            "{{\"temperature\": 22, \"unit\": \"{}\", \"condition\": \"sunny\"}}",
84            unit
85        );
86
87        // Continue the conversation with the function result
88        let final_response = client
89            .generate_content()
90            .with_system_prompt("You are a helpful weather assistant.")
91            .with_user_message("What's the weather like in San Francisco right now?")
92            .with_function_response_str("get_weather", weather_response)?
93            .with_generation_config(
94                GenerationConfig {
95                    temperature: Some(0.7),
96                    max_output_tokens: Some(100),
97                    ..Default::default()
98                }
99            )
100            .execute()
101            .await?;
102
103        println!("Final response: {}", final_response.text());
104    } else {
105        println!("No function calls in the response.");
106    }
107
108    Ok(())
109}
examples/tools.rs (line 26)
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}
Source

pub fn number(description: impl Into<String>) -> Self

Create a new number property

Examples found in repository?
examples/google_search_with_functions.rs (line 34)
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}
More examples
Hide additional examples
examples/tools.rs (line 54)
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}
Source

pub fn integer(description: impl Into<String>) -> Self

Create a new integer property

Source

pub fn boolean(description: impl Into<String>) -> Self

Create a new boolean property

Source

pub fn array(description: impl Into<String>, items: PropertyDetails) -> Self

Create a new array property

Source

pub fn enum_type( description: impl Into<String>, enum_values: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Create a new enum property

Examples found in repository?
examples/advanced.rs (lines 27-30)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let api_key = env::var("GEMINI_API_KEY")?;
11    
12    // Create client
13    let client = Gemini::new(api_key);
14    
15    // Define a weather function
16    let get_weather = FunctionDeclaration::new(
17        "get_weather",
18        "Get the current weather for a location",
19        FunctionParameters::object()
20            .with_property(
21                "location",
22                PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
23                true,
24            )
25            .with_property(
26                "unit",
27                PropertyDetails::enum_type(
28                    "The unit of temperature", 
29                    ["celsius", "fahrenheit"]
30                ),
31                false,
32            ),
33    );
34
35    // Create a request with function calling
36    println!("Sending function call request...");
37    let response = client
38        .generate_content()
39        .with_user_message("What's the weather like in Tokyo right now?")
40        .with_function(get_weather)
41        .with_function_calling_mode(FunctionCallingMode::Any)
42        .execute()
43        .await?;
44
45    // Check if there are function calls
46    if let Some(function_call) = response.function_calls().first() {
47        println!(
48            "Function call received: {} with args: {}",
49            function_call.name,
50            function_call.args
51        );
52
53        // Get parameters from the function call
54        let location: String = function_call.get("location")?;
55        let unit = function_call.get::<String>("unit").unwrap_or_else(|_| String::from("celsius"));
56        
57        println!("Location: {}, Unit: {}", location, unit);
58        
59        // Simulate function execution (in a real app, this would call a weather API)
60        // Create a JSON response object
61        let weather_response = serde_json::json!({
62            "temperature": 22,
63            "unit": unit,
64            "condition": "sunny",
65            "location": location
66        });
67
68        // Continue the conversation with the function result
69        // We need to replay the entire conversation with the function response
70        println!("Sending function response...");
71        
72        // First, need to recreate the original prompt and the model's response
73        let mut final_request = client.generate_content()
74            .with_user_message("What's the weather like in Tokyo right now?");
75        
76        // Add the function call from the model's response
77        let mut call_content = Content::default();
78        call_content.parts.push(Part::FunctionCall { 
79            function_call: (*function_call).clone()
80        });
81        let call_content = call_content.with_role(Role::Model);
82        final_request.contents.push(call_content);
83        
84        // Now add the function response using the JSON value
85        final_request = final_request.with_function_response("get_weather", weather_response);
86        
87        // Execute the request
88        let final_response = final_request.execute().await?;
89
90        println!("Final response: {}", final_response.text());
91    } else {
92        println!("No function calls in the response.");
93        println!("Response text: {}", response.text());
94    }
95
96    Ok(())
97}
More examples
Hide additional examples
examples/google_search_with_functions.rs (lines 26-29)
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}
examples/simple.rs (lines 49-52)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    // Get API key from environment variable
10    let api_key = env::var("GEMINI_API_KEY")
11        .expect("GEMINI_API_KEY environment variable not set");
12
13    // Create client
14    let client = Gemini::new(api_key);
15
16    // Simple generation
17    println!("--- Simple generation ---");
18    let response = client
19        .generate_content()
20        .with_system_prompt("You are a helpful assistant.")
21        .with_user_message("Hello, can you tell me a joke about programming?")
22        .with_generation_config(
23            GenerationConfig {
24                temperature: Some(0.7),
25                max_output_tokens: Some(100),
26                ..Default::default()
27            }
28        )
29        .execute()
30        .await?;
31
32    println!("Response: {}", response.text());
33
34    // Function calling example
35    println!("\n--- Function calling example ---");
36    
37    // Define a weather function
38    let get_weather = FunctionDeclaration::new(
39        "get_weather",
40        "Get the current weather for a location",
41        FunctionParameters::object()
42            .with_property(
43                "location",
44                PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
45                true,
46            )
47            .with_property(
48                "unit",
49                PropertyDetails::enum_type(
50                    "The unit of temperature", 
51                    ["celsius", "fahrenheit"]
52                ),
53                false,
54            ),
55    );
56
57    // Create a request with function calling
58    let response = client
59        .generate_content()
60        .with_system_prompt("You are a helpful weather assistant.")
61        .with_user_message("What's the weather like in San Francisco right now?")
62        .with_function(get_weather)
63        .with_function_calling_mode(FunctionCallingMode::Any)
64        .execute()
65        .await?;
66
67    // Check if there are function calls
68    if let Some(function_call) = response.function_calls().first() {
69        println!(
70            "Function call: {} with args: {}",
71            function_call.name,
72            function_call.args
73        );
74
75        // Get parameters from the function call
76        let location: String = function_call.get("location")?;
77        let unit = function_call.get::<String>("unit").unwrap_or_else(|_| String::from("celsius"));
78        
79        println!("Location: {}, Unit: {}", location, unit);
80        
81        // Simulate function execution
82        let weather_response = format!(
83            "{{\"temperature\": 22, \"unit\": \"{}\", \"condition\": \"sunny\"}}",
84            unit
85        );
86
87        // Continue the conversation with the function result
88        let final_response = client
89            .generate_content()
90            .with_system_prompt("You are a helpful weather assistant.")
91            .with_user_message("What's the weather like in San Francisco right now?")
92            .with_function_response_str("get_weather", weather_response)?
93            .with_generation_config(
94                GenerationConfig {
95                    temperature: Some(0.7),
96                    max_output_tokens: Some(100),
97                    ..Default::default()
98                }
99            )
100            .execute()
101            .await?;
102
103        println!("Final response: {}", final_response.text());
104    } else {
105        println!("No function calls in the response.");
106    }
107
108    Ok(())
109}
examples/tools.rs (lines 31-34)
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}

Trait Implementations§

Source§

impl Clone for PropertyDetails

Source§

fn clone(&self) -> PropertyDetails

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PropertyDetails

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for PropertyDetails

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for PropertyDetails

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T