pub struct GenerationResponse {
pub candidates: Vec<Candidate>,
pub prompt_feedback: Option<PromptFeedback>,
pub usage_metadata: Option<UsageMetadata>,
}
Expand description
Response from the Gemini API for content generation
Fields§
§candidates: Vec<Candidate>
The candidates generated
prompt_feedback: Option<PromptFeedback>
The prompt feedback
usage_metadata: Option<UsageMetadata>
Usage metadata
Implementations§
Source§impl GenerationResponse
impl GenerationResponse
Sourcepub fn text(&self) -> String
pub fn text(&self) -> String
Get the text of the first candidate
Examples found in repository?
examples/test_api.rs (line 20)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 let api_key = env::var("GEMINI_API_KEY")?;
7
8 // Create client with the default model (gemini-2.0-flash)
9 let client = Gemini::new(api_key);
10
11 println!("Sending request to Gemini API...");
12
13 // Simple text completion with minimal content
14 let response = client
15 .generate_content()
16 .with_user_message("Say hello")
17 .execute()
18 .await?;
19
20 println!("Response: {}", response.text());
21
22 Ok(())
23}
More examples
examples/google_search.rs (line 26)
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}
examples/curl_google_search.rs (line 54)
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/curl_equivalent.rs (line 38)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 // Get API key from environment variable
7 let api_key = env::var("GEMINI_API_KEY")
8 .expect("GEMINI_API_KEY environment variable not set");
9
10 // This is equivalent to the curl example:
11 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$YOUR_API_KEY" \
12 // -H 'Content-Type: application/json' \
13 // -X POST \
14 // -d '{
15 // "contents": [
16 // {
17 // "parts": [
18 // {
19 // "text": "Explain how AI works in a few words"
20 // }
21 // ]
22 // }
23 // ]
24 // }'
25
26 // Create client - now using gemini-2.0-flash by default
27 let client = Gemini::new(api_key);
28
29 // Method 1: Using the high-level API (simplest approach)
30 println!("--- Method 1: Using the high-level API ---");
31
32 let response = client
33 .generate_content()
34 .with_user_message("Explain how AI works in a few words")
35 .execute()
36 .await?;
37
38 println!("Response: {}", response.text());
39
40 // Method 2: Using Content directly to match the curl example exactly
41 println!("\n--- Method 2: Matching curl example structure exactly ---");
42
43 // Create a content part that matches the JSON in the curl example
44 let text_part = Part::Text {
45 text: "Explain how AI works in a few words".to_string()
46 };
47
48 let content = Content {
49 parts: vec![text_part],
50 role: None,
51 };
52
53 // Add the content directly to the request
54 // This exactly mirrors the JSON structure in the curl example
55 let mut content_builder = client.generate_content();
56 content_builder.contents.push(content);
57 let response = content_builder.execute().await?;
58
59 println!("Response: {}", response.text());
60
61 Ok(())
62}
examples/generation_config.rs (line 34)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 // Get API key from environment variable
7 let api_key = env::var("GEMINI_API_KEY")
8 .expect("GEMINI_API_KEY environment variable not set");
9
10 // Create client
11 let client = Gemini::new(api_key);
12
13 // Using the full generation config
14 println!("--- Using full generation config ---");
15 let response1 = client
16 .generate_content()
17 .with_system_prompt("You are a helpful assistant.")
18 .with_user_message("Write a short poem about Rust programming language.")
19 .with_generation_config(
20 GenerationConfig {
21 temperature: Some(0.9),
22 top_p: Some(0.8),
23 top_k: Some(20),
24 max_output_tokens: Some(200),
25 candidate_count: Some(1),
26 stop_sequences: Some(vec!["END".to_string()]),
27 response_mime_type: None,
28 response_schema: None,
29 }
30 )
31 .execute()
32 .await?;
33
34 println!("Response with high temperature (0.9):\n{}\n", response1.text());
35
36 // Using individual generation parameters
37 println!("--- Using individual generation parameters ---");
38 let response2 = client
39 .generate_content()
40 .with_system_prompt("You are a helpful assistant.")
41 .with_user_message("Write a short poem about Rust programming language.")
42 .with_temperature(0.2)
43 .with_max_output_tokens(100)
44 .execute()
45 .await?;
46
47 println!("Response with low temperature (0.2):\n{}\n", response2.text());
48
49 // Setting multiple parameters individually
50 println!("--- Setting multiple parameters individually ---");
51 let response3 = client
52 .generate_content()
53 .with_system_prompt("You are a helpful assistant.")
54 .with_user_message("List 3 benefits of using Rust.")
55 .with_temperature(0.7)
56 .with_top_p(0.9)
57 .with_max_output_tokens(150)
58 .with_stop_sequences(vec!["4.".to_string()])
59 .execute()
60 .await?;
61
62 println!("Response with custom parameters and stop sequence:\n{}", response3.text());
63
64 Ok(())
65}
examples/structured_response.rs (line 58)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Get API key from environment variable
8 let api_key = env::var("GEMINI_API_KEY")
9 .expect("GEMINI_API_KEY environment variable not set");
10
11 // Create client
12 let client = Gemini::new(api_key);
13
14 // Using response_schema for structured output
15 println!("--- Structured Response Example ---");
16
17 // Define a JSON schema for the response
18 let schema = json!({
19 "type": "object",
20 "properties": {
21 "name": {
22 "type": "string",
23 "description": "Name of the programming language"
24 },
25 "year_created": {
26 "type": "integer",
27 "description": "Year the programming language was created"
28 },
29 "creator": {
30 "type": "string",
31 "description": "Person or organization who created the language"
32 },
33 "key_features": {
34 "type": "array",
35 "items": {
36 "type": "string"
37 },
38 "description": "Key features of the programming language"
39 },
40 "popularity_score": {
41 "type": "integer",
42 "description": "Subjective popularity score from 1-10"
43 }
44 },
45 "required": ["name", "year_created", "creator", "key_features", "popularity_score"]
46 });
47
48 let response = client
49 .generate_content()
50 .with_system_prompt("You provide information about programming languages in JSON format.")
51 .with_user_message("Tell me about the Rust programming language.")
52 .with_response_mime_type("application/json")
53 .with_response_schema(schema)
54 .execute()
55 .await?;
56
57 println!("Structured JSON Response:");
58 println!("{}", response.text());
59
60 // Parse the JSON response
61 let json_response: serde_json::Value = serde_json::from_str(&response.text())?;
62
63 println!("\nAccessing specific fields:");
64 println!("Language: {}", json_response["name"]);
65 println!("Created in: {}", json_response["year_created"]);
66 println!("Created by: {}", json_response["creator"]);
67 println!("Popularity: {}/10", json_response["popularity_score"]);
68
69 println!("\nKey Features:");
70 if let Some(features) = json_response["key_features"].as_array() {
71 for (i, feature) in features.iter().enumerate() {
72 println!("{}. {}", i+1, feature);
73 }
74 }
75
76 Ok(())
77}
Additional examples can be found in:
Sourcepub fn function_calls(&self) -> Vec<&FunctionCall>
pub fn function_calls(&self) -> Vec<&FunctionCall>
Get function calls from the response
Examples found in repository?
examples/advanced.rs (line 46)
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
examples/google_search_with_functions.rs (line 61)
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 (line 68)
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 78)
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 GenerationResponse
impl Clone for GenerationResponse
Source§fn clone(&self) -> GenerationResponse
fn clone(&self) -> GenerationResponse
Returns a copy of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moreSource§impl Debug for GenerationResponse
impl Debug for GenerationResponse
Source§impl<'de> Deserialize<'de> for GenerationResponse
impl<'de> Deserialize<'de> for GenerationResponse
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 GenerationResponse
impl RefUnwindSafe for GenerationResponse
impl Send for GenerationResponse
impl Sync for GenerationResponse
impl Unpin for GenerationResponse
impl UnwindSafe for GenerationResponse
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