Struct Client

Source
pub struct Client {
    pub client: Client,
    pub api_key: String,
    pub model: String,
    pub api_url: Url,
}
Expand description

Gemini API client structure.

Fieldsยง

ยงclient: Client

Reqwest client instance.

ยงapi_key: String

API key for authentication.

ยงmodel: String

Model to be used.

ยงapi_url: Url

API URL for Gemini.

Implementationsยง

Sourceยง

impl Client

Source

pub fn new(api_key: &str, model: &str) -> Self

Creates a new instance of the Gemini Client.

ยงArguments
  • api_key - A static string representing the API key for authentication.
  • model - A static string representing the model to be used.
ยงReturns

A new instance of the Gemini Client.

ยงPanics

Panics if there is an issue parsing the Gemini API URL.

ยงExamples
use gems::Client;

let client = Client::new("your_api_key", "your_model");
Source

pub async fn generate_content( &mut self, text: &str, ) -> Result<String, Box<dyn Error>>

Generates content using the Gemini API.

ยงArguments
  • text - A static string representing the input text for content generation.
ยงReturns

A Result containing the generated content as a string or a reqwest::Error on failure.

ยงExamples
use gems::Client;

#[tokio::main]
async fn main() {
    let mut client = Client::new("your_api_key", "your_model");
    let result = client.generate_content("input_text").await;
    match result {
        Ok(content) => println!("Generated Content: {}", content),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}
Source

pub async fn stream_generate_content( &mut self, text: &str, ) -> Result<Response, Box<dyn Error>>

Streams generated content using the Gemini API and prints it with a delay effect.

ยงArguments
  • text - A static string representing the input text for content generation.
  • suppress - A boolean to decide whether or not to print the content being generated
ยงReturns

A Result indicating success or a Box on failure.

ยงExamples
use futures_util::StreamExt;
use gems::Client;
use gems::utils::{
    extract_text_from_partial_json, type_with_cursor_effect,
};

#[tokio::main]
async fn main() {
    let mut client = Client::new("your_api_key", "your_model");
    let result = client.stream_generate_content("input_text").await;
    let mut stream = result.expect("response").bytes_stream();
    let delay = 5;
    let mut message: String = Default::default();
    while let Some(mut chunk) = stream.next().await {
        if let Ok(parsed_json) = std::str::from_utf8(chunk.as_mut().unwrap()) {
            if let Some(text_value) = extract_text_from_partial_json(parsed_json) {
                let lines: Vec<&str> = text_value
                    .split("\\n")
                    .flat_map(|s| s.split('\n'))
                    .collect();
     
                for line in lines {
                    message.push_str(&line.replace('\\', ""));
                    if !line.is_empty() {
                        type_with_cursor_effect(&line.replace('\\', ""), delay);
                    } else {
                        println!("\n");
                    }
                }
            }
        } else {
            eprintln!("Failed to parse chunk: {:?}", chunk.as_ref().unwrap());
        }
    }
}
Source

pub async fn count_tokens(&mut self, text: &str) -> Result<usize, Error>

Counts the number of tokens in the provided text using the Gemini API.

ยงArguments
  • text - A static string representing the input text for token counting.
ยงReturns

A Result containing the count of tokens as usize or a reqwest::Error on failure.

ยงExamples
use gems::Client;

#[tokio::main]
async fn main() {
    let mut client = Client::new("your_api_key", "your_model");
    let result = client.count_tokens("input_text").await;
    match result {
        Ok(count) => println!("Token Count: {}", count),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}
Source

pub async fn get_model_info(&mut self) -> Result<ModelInfo, Error>

Retrieves information about the specified model using the Gemini API.

ยงReturns

A Result containing model information or a reqwest::Error on failure.

ยงExamples
use gems::Client;

#[tokio::main]
async fn main() {
    let mut client = Client::new("your_api_key", "your_model");
    let result = client.get_model_info().await;
    match result {
        Ok(info) => println!("Model Info: {:?}", info),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}
Source

pub async fn embed_content( &mut self, text: &str, ) -> Result<EmbedContentResponse, Error>

Embeds content using the Gemini API.

ยงArguments
  • text - A static string representing the input text for content embedding.
ยงReturns

A Result containing the embedded content response or a reqwest::Error on failure.

ยงExamples
use gems::Client;

#[tokio::main]
async fn main() {
    let mut client = Client::new("your_api_key", "your_model");
    let result = client.embed_content("input_text").await;
    match result {
        Ok(response) => println!("Embedded Content: {:?}", response),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}
Source

pub async fn batch_embed_contents( &mut self, texts: Vec<&str>, ) -> Result<BatchEmbedContentsResponse, Error>

Batch embeds multiple contents using the Gemini API.

ยงArguments
  • texts - A vector of static strings representing the input texts for batch embedding.
ยงReturns

A Result containing the batch embedded contents response or a reqwest::Error on failure.

ยงExamples
use gems::Client;

#[tokio::main]
async fn main() {
    let mut client = Client::new("your_api_key", "your_model");
    let texts = vec!["text1", "text2", "text3"];
    let result = client.batch_embed_contents(texts).await;
    match result {
        Ok(response) => println!("Batch Embedded Contents: {:?}", response),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}
Source

pub async fn list_models(&self) -> Result<ModelsResponse, Error>

Retrieves a list of available models from the Gemini API.

ยงReturns

A Result containing the list of models or a reqwest::Error on failure.

ยงExamples
use gems::Client;

#[tokio::main]
async fn main() {
    let client = Client::new("your_api_key", "your_model");
    let result = client.list_models().await;
    match result {
        Ok(models) => println!("Available Models: {:?}", models),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}
Source

pub async fn generate_content_with_image( &mut self, text: &str, image_data: &str, ) -> Result<String, Box<dyn Error>>

Generates content using the Gemini API with both text and image input.

ยงArguments
  • text - A static string representing the input text for content generation.
  • image_data - A base64-encoded string representing the image data.
ยงReturns

A Result containing the generated content as a string or a reqwest::Error on failure.

ยงExamples
use gems::Client;

#[tokio::main]
async fn main() {
    let mut client = Client::new("your_api_key", "your_model");
    let result = client.generate_content_with_image("What is this picture?", "base64_encoded_image_data").await;
    match result {
        Ok(content) => println!("Generated Content: {}", content),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}

Trait Implementationsยง

Sourceยง

impl Clone for Client

Sourceยง

fn clone(&self) -> Client

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 Client

Sourceยง

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

Formats the value using the given formatter. 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> ErasedDestructor for T
where T: 'static,

Sourceยง

impl<T> MaybeSendSync for T