Struct Gemini

Source
pub struct Gemini { /* private fields */ }
Expand description

Client for the Gemini API

Implementations§

Source§

impl Gemini

Source

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
Hide additional 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}
Source

pub fn pro(api_key: impl Into<String>) -> Self

Create a new client for the Gemini Pro model

Source

pub fn with_model(api_key: impl Into<String>, model: String) -> Self

Create a new client with the specified API key and model

Source

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
Hide additional 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}

Trait Implementations§

Source§

impl Clone for Gemini

Source§

fn clone(&self) -> Gemini

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

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> 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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T