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 10)
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").expect("GEMINI_API_KEY environment variable not set");
8
9 // Create client
10 let client = Gemini::new(api_key);
11
12 println!("--- Google Search tool example ---");
13
14 // Create a Google Search tool
15 let google_search_tool = Tool::google_search();
16
17 // Create a request with Google Search tool
18 let response = client
19 .generate_content()
20 .with_user_message("What is the current Google stock price?")
21 .with_tool(google_search_tool)
22 .execute()
23 .await?;
24
25 println!("Response: {}", response.text());
26
27 Ok(())
28}
examples/blob.rs (line 30)
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 // Image file path (in the same directory)
14 let image_path = Path::new(file!())
15 .parent()
16 .unwrap_or(Path::new("."))
17 .join("image-example.webp"); // Replace with your image filename
18
19 // Read the image file
20 let mut file = File::open(&image_path)?;
21 let mut buffer = Vec::new();
22 file.read_to_end(&mut buffer)?;
23
24 // Convert to base64
25 let data = general_purpose::STANDARD.encode(&buffer);
26
27 println!("Image loaded: {}", image_path.display());
28
29 // Create client
30 let client = Gemini::new(api_key);
31
32 println!("--- Describe Image ---");
33 let response = client
34 .generate_content()
35 .with_inline_data(data, "image/webp")
36 .with_response_mime_type("text/plain")
37 .with_generation_config(GenerationConfig {
38 temperature: Some(0.7),
39 max_output_tokens: Some(400),
40 ..Default::default()
41 })
42 .execute()
43 .await?;
44
45 println!("Response: {}", response.text());
46
47 Ok(())
48}
examples/curl_google_search.rs (line 30)
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").expect("GEMINI_API_KEY environment variable not set");
8
9 println!("--- Curl equivalent with Google Search tool ---");
10
11 // This is equivalent to the curl example:
12 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
13 // -H "Content-Type: application/json" \
14 // -d '{
15 // "contents": [
16 // {
17 // "parts": [
18 // {"text": "What is the current Google stock price?"}
19 // ]
20 // }
21 // ],
22 // "tools": [
23 // {
24 // "google_search": {}
25 // }
26 // ]
27 // }'
28
29 // Create client
30 let client = Gemini::new(api_key);
31
32 // Create a content part that matches the JSON in the curl example
33 let text_part = Part::Text {
34 text: "What is the current Google stock price?".to_string(),
35 };
36
37 let content = Content {
38 parts: vec![text_part],
39 role: None,
40 };
41
42 // Create a Google Search tool
43 let google_search_tool = Tool::google_search();
44
45 // Add the content and tool directly to the request
46 // This exactly mirrors the JSON structure in the curl example
47 let mut content_builder = client.generate_content();
48 content_builder.contents.push(content);
49 content_builder = content_builder.with_tool(google_search_tool);
50
51 let response = content_builder.execute().await?;
52
53 println!("Response: {}", response.text());
54
55 Ok(())
56}
examples/curl_equivalent.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("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
8
9 // This is equivalent to the curl example:
10 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$YOUR_API_KEY" \
11 // -H 'Content-Type: application/json' \
12 // -X POST \
13 // -d '{
14 // "contents": [
15 // {
16 // "parts": [
17 // {
18 // "text": "Explain how AI works in a few words"
19 // }
20 // ]
21 // }
22 // ]
23 // }'
24
25 // Create client - now using gemini-2.0-flash by default
26 let client = Gemini::new(api_key);
27
28 // Method 1: Using the high-level API (simplest approach)
29 println!("--- Method 1: Using the high-level API ---");
30
31 let response = client
32 .generate_content()
33 .with_user_message("Explain how AI works in a few words")
34 .execute()
35 .await?;
36
37 println!("Response: {}", response.text());
38
39 // Method 2: Using Content directly to match the curl example exactly
40 println!("\n--- Method 2: Matching curl example structure exactly ---");
41
42 // Create a content part that matches the JSON in the curl example
43 let text_part = Part::Text {
44 text: "Explain how AI works in a few words".to_string(),
45 };
46
47 let content = Content {
48 parts: vec![text_part],
49 role: None,
50 };
51
52 // Add the content directly to the request
53 // This exactly mirrors the JSON structure in the curl example
54 let mut content_builder = client.generate_content();
55 content_builder.contents.push(content);
56 let response = content_builder.execute().await?;
57
58 println!("Response: {}", response.text());
59
60 Ok(())
61}
examples/generation_config.rs (line 10)
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").expect("GEMINI_API_KEY environment variable not set");
8
9 // Create client
10 let client = Gemini::new(api_key);
11
12 // Using the full generation config
13 println!("--- Using full generation config ---");
14 let response1 = client
15 .generate_content()
16 .with_system_prompt("You are a helpful assistant.")
17 .with_user_message("Write a short poem about Rust programming language.")
18 .with_generation_config(GenerationConfig {
19 temperature: Some(0.9),
20 top_p: Some(0.8),
21 top_k: Some(20),
22 max_output_tokens: Some(200),
23 candidate_count: Some(1),
24 stop_sequences: Some(vec!["END".to_string()]),
25 response_mime_type: None,
26 response_schema: None,
27 })
28 .execute()
29 .await?;
30
31 println!(
32 "Response with high temperature (0.9):\n{}\n",
33 response1.text()
34 );
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!(
48 "Response with low temperature (0.2):\n{}\n",
49 response2.text()
50 );
51
52 // Setting multiple parameters individually
53 println!("--- Setting multiple parameters individually ---");
54 let response3 = client
55 .generate_content()
56 .with_system_prompt("You are a helpful assistant.")
57 .with_user_message("List 3 benefits of using Rust.")
58 .with_temperature(0.7)
59 .with_top_p(0.9)
60 .with_max_output_tokens(150)
61 .with_stop_sequences(vec!["4.".to_string()])
62 .execute()
63 .await?;
64
65 println!(
66 "Response with custom parameters and stop sequence:\n{}",
67 response3.text()
68 );
69
70 Ok(())
71}
Sourcepub fn pro(api_key: impl Into<String>) -> Self
pub fn pro(api_key: impl Into<String>) -> Self
Create a new client for the Gemini Pro model
Examples found in repository?
examples/gemini_pro_example.rs (line 11)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Replace with your actual API key
8 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
9
10 // Create a Gemini client
11 let gemini = Gemini::pro(api_key);
12
13 // This example matches the exact curl request format:
14 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
15 // -H 'Content-Type: application/json' \
16 // -d '{
17 // "system_instruction": {
18 // "parts": [
19 // {
20 // "text": "You are a cat. Your name is Neko."
21 // }
22 // ]
23 // },
24 // "contents": [
25 // {
26 // "parts": [
27 // {
28 // "text": "Hello there"
29 // }
30 // ]
31 // }
32 // ]
33 // }'
34 let response = gemini
35 .generate_content()
36 .with_system_instruction("You are a cat. Your name is Neko.")
37 .with_user_message("Hello there")
38 .execute()
39 .await?;
40
41 // Print the response
42 println!("Response: {}", response.text());
43
44 Ok(())
45}
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
Examples found in repository?
examples/embedding.rs (line 8)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 let api_key = std::env::var("GEMINI_API_KEY")?;
6
7 // Create client with the default model (gemini-2.0-flash)
8 let client = Gemini::with_model(api_key, "models/text-embedding-004".to_string());
9
10 println!("Sending embedding request to Gemini API...");
11
12 // Simple text embedding
13 let response = client
14 .embed_content()
15 .with_text("Hello")
16 .with_task_type(TaskType::RetrievalDocument)
17 .execute()
18 .await?;
19
20 println!("Response: {:?}", response.embedding.values);
21
22 Ok(())
23}
More examples
examples/batch_embedding.rs (line 8)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 let api_key = std::env::var("GEMINI_API_KEY")?;
6
7 // Create client with the default model (gemini-2.0-flash)
8 let client = Gemini::with_model(api_key, "models/text-embedding-004".to_string());
9
10 println!("Sending batch embedding request to Gemini API...");
11
12 // Simple text embedding
13 let response = client
14 .embed_content()
15 .with_chunks(vec!["Hello", "World", "Test embedding 3"])
16 .with_task_type(TaskType::RetrievalDocument)
17 .execute_batch()
18 .await?;
19
20 println!("Response: ");
21 for (i, e) in response.embeddings.iter().enumerate() {
22 println!("|{}|: {:?}\n", i, e.values);
23 }
24
25 Ok(())
26}
Sourcepub fn with_base_url(api_key: impl Into<String>, base_url: String) -> Self
pub fn with_base_url(api_key: impl Into<String>, base_url: String) -> Self
Create a new client with custom base URL
Sourcepub fn with_model_and_base_url(
api_key: impl Into<String>,
model: String,
base_url: String,
) -> Self
pub fn with_model_and_base_url( api_key: impl Into<String>, model: String, base_url: String, ) -> Self
Create a new client with the specified API key, model, and base URL
Examples found in repository?
examples/custom_base_url.rs (lines 10-14)
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").expect("GEMINI_API_KEY environment variable not set");
8 // Using custom base URL
9 let custom_base_url = "https://generativelanguage.googleapis.com/v1beta/";
10 let client_custom = Gemini::with_model_and_base_url(
11 api_key,
12 "models/gemini-2.5-flash-lite-preview-06-17".to_string(),
13 custom_base_url.to_string(),
14 );
15 println!("Custom base URL client created successfully");
16 let response = client_custom
17 .generate_content()
18 .with_system_prompt("You are a helpful assistant.")
19 .with_user_message("Hello, can you tell me a joke about programming?")
20 .with_generation_config(GenerationConfig {
21 temperature: Some(0.7),
22 max_output_tokens: Some(100),
23 ..Default::default()
24 })
25 .execute()
26 .await?;
27
28 println!("Response: {}", response.text());
29
30 Ok(())
31}
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 19)
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").expect("GEMINI_API_KEY environment variable not set");
8
9 // Create client
10 let client = Gemini::new(api_key);
11
12 println!("--- Google Search tool example ---");
13
14 // Create a Google Search tool
15 let google_search_tool = Tool::google_search();
16
17 // Create a request with Google Search tool
18 let response = client
19 .generate_content()
20 .with_user_message("What is the current Google stock price?")
21 .with_tool(google_search_tool)
22 .execute()
23 .await?;
24
25 println!("Response: {}", response.text());
26
27 Ok(())
28}
examples/custom_base_url.rs (line 17)
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").expect("GEMINI_API_KEY environment variable not set");
8 // Using custom base URL
9 let custom_base_url = "https://generativelanguage.googleapis.com/v1beta/";
10 let client_custom = Gemini::with_model_and_base_url(
11 api_key,
12 "models/gemini-2.5-flash-lite-preview-06-17".to_string(),
13 custom_base_url.to_string(),
14 );
15 println!("Custom base URL client created successfully");
16 let response = client_custom
17 .generate_content()
18 .with_system_prompt("You are a helpful assistant.")
19 .with_user_message("Hello, can you tell me a joke about programming?")
20 .with_generation_config(GenerationConfig {
21 temperature: Some(0.7),
22 max_output_tokens: Some(100),
23 ..Default::default()
24 })
25 .execute()
26 .await?;
27
28 println!("Response: {}", response.text());
29
30 Ok(())
31}
examples/gemini_pro_example.rs (line 35)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Replace with your actual API key
8 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
9
10 // Create a Gemini client
11 let gemini = Gemini::pro(api_key);
12
13 // This example matches the exact curl request format:
14 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
15 // -H 'Content-Type: application/json' \
16 // -d '{
17 // "system_instruction": {
18 // "parts": [
19 // {
20 // "text": "You are a cat. Your name is Neko."
21 // }
22 // ]
23 // },
24 // "contents": [
25 // {
26 // "parts": [
27 // {
28 // "text": "Hello there"
29 // }
30 // ]
31 // }
32 // ]
33 // }'
34 let response = gemini
35 .generate_content()
36 .with_system_instruction("You are a cat. Your name is Neko.")
37 .with_user_message("Hello there")
38 .execute()
39 .await?;
40
41 // Print the response
42 println!("Response: {}", response.text());
43
44 Ok(())
45}
examples/blob.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("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
12
13 // Image file path (in the same directory)
14 let image_path = Path::new(file!())
15 .parent()
16 .unwrap_or(Path::new("."))
17 .join("image-example.webp"); // Replace with your image filename
18
19 // Read the image file
20 let mut file = File::open(&image_path)?;
21 let mut buffer = Vec::new();
22 file.read_to_end(&mut buffer)?;
23
24 // Convert to base64
25 let data = general_purpose::STANDARD.encode(&buffer);
26
27 println!("Image loaded: {}", image_path.display());
28
29 // Create client
30 let client = Gemini::new(api_key);
31
32 println!("--- Describe Image ---");
33 let response = client
34 .generate_content()
35 .with_inline_data(data, "image/webp")
36 .with_response_mime_type("text/plain")
37 .with_generation_config(GenerationConfig {
38 temperature: Some(0.7),
39 max_output_tokens: Some(400),
40 ..Default::default()
41 })
42 .execute()
43 .await?;
44
45 println!("Response: {}", response.text());
46
47 Ok(())
48}
examples/curl_google_search.rs (line 47)
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").expect("GEMINI_API_KEY environment variable not set");
8
9 println!("--- Curl equivalent with Google Search tool ---");
10
11 // This is equivalent to the curl example:
12 // curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
13 // -H "Content-Type: application/json" \
14 // -d '{
15 // "contents": [
16 // {
17 // "parts": [
18 // {"text": "What is the current Google stock price?"}
19 // ]
20 // }
21 // ],
22 // "tools": [
23 // {
24 // "google_search": {}
25 // }
26 // ]
27 // }'
28
29 // Create client
30 let client = Gemini::new(api_key);
31
32 // Create a content part that matches the JSON in the curl example
33 let text_part = Part::Text {
34 text: "What is the current Google stock price?".to_string(),
35 };
36
37 let content = Content {
38 parts: vec![text_part],
39 role: None,
40 };
41
42 // Create a Google Search tool
43 let google_search_tool = Tool::google_search();
44
45 // Add the content and tool directly to the request
46 // This exactly mirrors the JSON structure in the curl example
47 let mut content_builder = client.generate_content();
48 content_builder.contents.push(content);
49 content_builder = content_builder.with_tool(google_search_tool);
50
51 let response = content_builder.execute().await?;
52
53 println!("Response: {}", response.text());
54
55 Ok(())
56}
Sourcepub fn embed_content(&self) -> EmbedBuilder
pub fn embed_content(&self) -> EmbedBuilder
Start building a content generation request
Examples found in repository?
examples/embedding.rs (line 14)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 let api_key = std::env::var("GEMINI_API_KEY")?;
6
7 // Create client with the default model (gemini-2.0-flash)
8 let client = Gemini::with_model(api_key, "models/text-embedding-004".to_string());
9
10 println!("Sending embedding request to Gemini API...");
11
12 // Simple text embedding
13 let response = client
14 .embed_content()
15 .with_text("Hello")
16 .with_task_type(TaskType::RetrievalDocument)
17 .execute()
18 .await?;
19
20 println!("Response: {:?}", response.embedding.values);
21
22 Ok(())
23}
More examples
examples/batch_embedding.rs (line 14)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 let api_key = std::env::var("GEMINI_API_KEY")?;
6
7 // Create client with the default model (gemini-2.0-flash)
8 let client = Gemini::with_model(api_key, "models/text-embedding-004".to_string());
9
10 println!("Sending batch embedding request to Gemini API...");
11
12 // Simple text embedding
13 let response = client
14 .embed_content()
15 .with_chunks(vec!["Hello", "World", "Test embedding 3"])
16 .with_task_type(TaskType::RetrievalDocument)
17 .execute_batch()
18 .await?;
19
20 println!("Response: ");
21 for (i, e) in response.embeddings.iter().enumerate() {
22 println!("|{}|: {:?}\n", i, e.values);
23 }
24
25 Ok(())
26}
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