pub struct Gemini { /* private fields */ }
Expand description
Client for the Gemini API
Implementations§
Source§impl Gemini
impl Gemini
Sourcepub fn new(api_key: impl Into<String>) -> Self
pub fn new(api_key: impl Into<String>) -> Self
Create a new client with the specified API key
Examples found in repository?
examples/test_api.rs (line 9)
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 11)
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 31)
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 27)
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 11)
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 12)
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 with_model(api_key: impl Into<String>, model: String) -> Self
pub fn with_model(api_key: impl Into<String>, model: String) -> Self
Create a new client with the specified API key and model
Sourcepub fn generate_content(&self) -> ContentBuilder
pub fn generate_content(&self) -> ContentBuilder
Start building a content generation request
Examples found in repository?
examples/test_api.rs (line 15)
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 20)
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 48)
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 33)
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 16)
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 49)
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:
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Gemini
impl !RefUnwindSafe for Gemini
impl Send for Gemini
impl Sync for Gemini
impl Unpin for Gemini
impl !UnwindSafe for Gemini
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