pub struct Client { /* private fields */ }Expand description
The main client for interacting with the Google Generative AI API.
Implementations§
Source§impl Client
impl Client
Sourcepub const fn builder(api_key: String) -> ClientBuilder
pub const fn builder(api_key: String) -> ClientBuilder
Sourcepub fn interaction(&self) -> InteractionBuilder<'_>
pub fn interaction(&self) -> InteractionBuilder<'_>
Creates a builder for constructing an interaction request.
This provides a fluent interface for building interactions with models or agents.
Use this method for a more ergonomic API compared to manually constructing
InteractionRequest.
§Examples
let client = Client::builder("api_key".to_string()).build()?;
// Simple interaction
let response = client.interaction()
.with_model("gemini-3-flash-preview")
.with_text("Hello, world!")
.create()
.await?;
// Stateful conversation (requires stored interaction)
let response2 = client.interaction()
.with_model("gemini-3-flash-preview")
.with_text("What did I just say?")
.with_previous_interaction(response.id.as_ref().expect("stored interaction has id"))
.create()
.await?;Sourcepub async fn execute(
&self,
request: InteractionRequest,
) -> Result<InteractionResponse, GenaiError>
pub async fn execute( &self, request: InteractionRequest, ) -> Result<InteractionResponse, GenaiError>
Creates a new interaction using the Gemini Interactions API.
The Interactions API provides a unified interface for working with models and agents, with built-in support for stateful conversations, function calling, and long-running tasks.
§Arguments
request- The interaction request with model/agent, input, and optional configuration.
§Errors
Returns an error if:
- The HTTP request fails
- Response parsing fails
- The API returns an error
§Example
use genai_rs::Client;
use genai_rs::{InteractionRequest, InteractionInput};
let client = Client::new("your-api-key".to_string());
let request = InteractionRequest {
model: Some("gemini-3-flash-preview".to_string()),
agent: None,
agent_config: None,
input: InteractionInput::Text("Hello, world!".to_string()),
previous_interaction_id: None,
tools: None,
response_modalities: None,
response_format: None,
response_mime_type: None,
generation_config: None,
stream: None,
background: None,
store: None,
system_instruction: None,
};
let response = client.execute(request).await?;
println!("Interaction ID: {:?}", response.id);§Streaming Example
use genai_rs::{Client, StreamChunk};
use genai_rs::{InteractionRequest, InteractionInput};
use futures_util::StreamExt;
let client = Client::builder("api_key".to_string()).build()?;
let request = InteractionRequest {
model: Some("gemini-3-flash-preview".to_string()),
agent: None,
agent_config: None,
input: InteractionInput::Text("Count to 5".to_string()),
previous_interaction_id: None,
tools: None,
response_modalities: None,
response_format: None,
response_mime_type: None,
generation_config: None,
stream: Some(true),
background: None,
store: None,
system_instruction: None,
};
let mut last_event_id = None;
let mut stream = client.execute_stream(request);
while let Some(result) = stream.next().await {
let event = result?;
last_event_id = event.event_id.clone(); // Track for resume
match event.chunk {
StreamChunk::Delta(delta) => {
if let Some(text) = delta.as_text() {
print!("{}", text);
}
}
StreamChunk::Complete(response) => {
println!("\nDone! ID: {:?}", response.id);
}
_ => {} // Handle unknown future variants
}
}§Retry Example
use genai_rs::Client;
use std::time::Duration;
let client = Client::new("api_key".to_string());
let request = client.interaction()
.with_model("gemini-3-flash-preview")
.with_text("Hello!")
.build()?;
// Retry loop with exponential backoff
let mut attempts = 0;
let response = loop {
match client.execute(request.clone()).await {
Ok(r) => break r,
Err(e) if e.is_retryable() && attempts < 3 => {
attempts += 1;
tokio::time::sleep(Duration::from_millis(100 * 2u64.pow(attempts))).await;
}
Err(e) => return Err(e.into()),
}
};Sourcepub fn execute_stream(
&self,
request: InteractionRequest,
) -> BoxStream<'_, Result<StreamEvent, GenaiError>>
pub fn execute_stream( &self, request: InteractionRequest, ) -> BoxStream<'_, Result<StreamEvent, GenaiError>>
Executes a pre-built interaction request with streaming.
This is the streaming variant of execute().
Returns a stream of StreamEvent items as they arrive.
Each event contains:
chunk: The content (delta or complete response)event_id: Optional ID for resuming interrupted streams
§Example
use genai_rs::{Client, StreamChunk};
use futures_util::StreamExt;
let client = Client::new("api_key".to_string());
let request = client.interaction()
.with_model("gemini-3-flash-preview")
.with_text("Count to 5")
.build()?;
let mut stream = client.execute_stream(request);
while let Some(result) = stream.next().await {
let event = result?;
match event.chunk {
StreamChunk::Delta(delta) => {
if let Some(text) = delta.as_text() {
print!("{}", text);
}
}
StreamChunk::Complete(response) => {
println!("\nDone!");
}
_ => {}
}
}Sourcepub async fn get_interaction(
&self,
interaction_id: &str,
) -> Result<InteractionResponse, GenaiError>
pub async fn get_interaction( &self, interaction_id: &str, ) -> Result<InteractionResponse, GenaiError>
Retrieves an existing interaction by its ID.
Useful for checking the status of long-running interactions or agents, or for retrieving the full conversation history.
§Arguments
interaction_id- The unique identifier of the interaction to retrieve.
§Errors
Returns an error if:
- The HTTP request fails
- Response parsing fails
- The API returns an error
Sourcepub fn get_interaction_stream<'a>(
&'a self,
interaction_id: &'a str,
last_event_id: Option<&'a str>,
) -> BoxStream<'a, Result<StreamEvent, GenaiError>>
pub fn get_interaction_stream<'a>( &'a self, interaction_id: &'a str, last_event_id: Option<&'a str>, ) -> BoxStream<'a, Result<StreamEvent, GenaiError>>
Retrieves an existing interaction by its ID with streaming.
Returns a stream of events for the interaction. This is useful for:
- Resuming an interrupted stream using
last_event_id - Streaming a long-running interaction’s progress (e.g., deep research)
Each event includes an event_id that can be used to resume the stream
from that point if the connection is interrupted.
§Arguments
interaction_id- The unique identifier of the interaction to stream.last_event_id- Optional event ID to resume from. Pass the last received event’sevent_idto continue from where you left off.
§Returns
A boxed stream that yields StreamEvent items.
§Example
use genai_rs::{Client, StreamChunk};
use futures_util::StreamExt;
let client = Client::builder("api_key".to_string()).build()?;
let interaction_id = "some-interaction-id";
// Resume a stream from a previous event
let last_event_id = Some("evt_abc123");
let mut stream = client.get_interaction_stream(interaction_id, last_event_id);
while let Some(result) = stream.next().await {
let event = result?;
println!("Event ID: {:?}", event.event_id);
match event.chunk {
StreamChunk::Delta(delta) => {
if let Some(text) = delta.as_text() {
print!("{}", text);
}
}
StreamChunk::Complete(response) => {
println!("\nDone! Status: {:?}", response.status);
}
_ => {}
}
}Sourcepub async fn delete_interaction(
&self,
interaction_id: &str,
) -> Result<(), GenaiError>
pub async fn delete_interaction( &self, interaction_id: &str, ) -> Result<(), GenaiError>
Deletes an interaction by its ID.
Removes the interaction from the server, freeing up storage and making it
unavailable for future reference via previous_interaction_id.
§Arguments
interaction_id- The unique identifier of the interaction to delete.
§Errors
Returns an error if:
- The HTTP request fails
- The API returns an error
Sourcepub async fn cancel_interaction(
&self,
interaction_id: &str,
) -> Result<InteractionResponse, GenaiError>
pub async fn cancel_interaction( &self, interaction_id: &str, ) -> Result<InteractionResponse, GenaiError>
Cancels an in-progress background interaction.
Only applicable to interactions created with background: true that are
still in InProgress status. Returns the updated interaction with
status Cancelled.
This is useful for:
- Halting long-running agent tasks (e.g., deep-research) when requirements change
- Cost control by stopping interactions consuming significant tokens
- Implementing timeout handling in application logic
- Supporting user-initiated cancellation in UIs
§Arguments
interaction_id- The unique identifier of the interaction to cancel.
§Errors
Returns an error if:
- The interaction doesn’t exist
- The interaction is not in a cancellable state (not background or already complete)
- The HTTP request fails
- The API returns an error
§Example
use genai_rs::{Client, InteractionStatus};
let client = Client::new("your-api-key".to_string());
// Start a background agent interaction
let response = client.interaction()
.with_agent("deep-research-pro-preview-12-2025")
.with_text("Research AI safety")
.with_background(true)
.with_store_enabled()
.create()
.await?;
let interaction_id = response.id.as_ref().expect("stored interaction has id");
// Later, cancel if still in progress
if response.status == InteractionStatus::InProgress {
let cancelled = client.cancel_interaction(interaction_id).await?;
assert_eq!(cancelled.status, InteractionStatus::Cancelled);
println!("Interaction cancelled");
}Sourcepub async fn upload_file(
&self,
path: impl AsRef<Path>,
) -> Result<FileMetadata, GenaiError>
pub async fn upload_file( &self, path: impl AsRef<Path>, ) -> Result<FileMetadata, GenaiError>
Uploads a file from a path to the Files API.
Files are stored for 48 hours and can be referenced in interactions by their URI. This is more efficient than inline base64 encoding for large files or files that will be used across multiple interactions.
§Arguments
path- Path to the file to upload
§Errors
Returns an error if:
- The file cannot be read
- The MIME type cannot be determined
- The upload fails
§Example
use genai_rs::{Client, Content};
let client = Client::new("api-key".to_string());
// Upload a video file
let file = client.upload_file("video.mp4").await?;
println!("Uploaded: {} -> {}", file.name, file.uri);
// Use in interaction
let response = client.interaction()
.with_model("gemini-3-flash-preview")
.with_content(vec![
Content::text("Describe this video"),
Content::from_file(&file),
])
.create()
.await?;Sourcepub async fn upload_file_with_mime(
&self,
path: impl AsRef<Path>,
mime_type: &str,
) -> Result<FileMetadata, GenaiError>
pub async fn upload_file_with_mime( &self, path: impl AsRef<Path>, mime_type: &str, ) -> Result<FileMetadata, GenaiError>
Uploads a file with an explicit MIME type.
Use this when automatic MIME type detection isn’t suitable.
§Arguments
path- Path to the file to uploadmime_type- MIME type of the file (e.g., “video/mp4”)
§Example
use genai_rs::Client;
let client = Client::new("api-key".to_string());
let file = client.upload_file_with_mime("data.bin", "application/octet-stream").await?;Sourcepub async fn upload_file_bytes(
&self,
data: Vec<u8>,
mime_type: &str,
display_name: Option<&str>,
) -> Result<FileMetadata, GenaiError>
pub async fn upload_file_bytes( &self, data: Vec<u8>, mime_type: &str, display_name: Option<&str>, ) -> Result<FileMetadata, GenaiError>
Uploads file bytes directly with a specified MIME type.
Use this when you already have file contents in memory.
§Arguments
data- File contents as bytesmime_type- MIME type of the filedisplay_name- Optional display name for the file
§Example
use genai_rs::Client;
let client = Client::new("api-key".to_string());
// Upload bytes from memory
let video_bytes = std::fs::read("video.mp4")?;
let file = client.upload_file_bytes(video_bytes, "video/mp4", Some("my-video")).await?;Sourcepub async fn get_file(
&self,
file_name: &str,
) -> Result<FileMetadata, GenaiError>
pub async fn get_file( &self, file_name: &str, ) -> Result<FileMetadata, GenaiError>
Gets metadata for an uploaded file.
Use this to check the processing status of a recently uploaded file.
§Arguments
file_name- The resource name of the file (e.g., “files/abc123”)
§Example
use genai_rs::Client;
let client = Client::new("api-key".to_string());
let file = client.get_file("files/abc123").await?;
if file.is_active() {
println!("File is ready to use");
} else if file.is_processing() {
println!("File is still processing...");
}Sourcepub async fn list_files(
&self,
page_size: Option<u32>,
page_token: Option<&str>,
) -> Result<ListFilesResponse, GenaiError>
pub async fn list_files( &self, page_size: Option<u32>, page_token: Option<&str>, ) -> Result<ListFilesResponse, GenaiError>
Lists all uploaded files.
§Example
use genai_rs::Client;
let client = Client::new("api-key".to_string());
let response = client.list_files(None, None).await?;
for file in response.files {
println!("{}: {} ({})", file.name, file.display_name.as_deref().unwrap_or(""), file.mime_type);
}Sourcepub async fn delete_file(&self, file_name: &str) -> Result<(), GenaiError>
pub async fn delete_file(&self, file_name: &str) -> Result<(), GenaiError>
Deletes an uploaded file.
§Arguments
file_name- The resource name of the file to delete (e.g., “files/abc123”)
§Example
use genai_rs::Client;
let client = Client::new("api-key".to_string());
// Upload, use, then delete
let file = client.upload_file("video.mp4").await?;
// ... use in interactions ...
client.delete_file(&file.name).await?;Sourcepub async fn upload_file_chunked(
&self,
path: impl AsRef<Path>,
) -> Result<(FileMetadata, ResumableUpload), GenaiError>
pub async fn upload_file_chunked( &self, path: impl AsRef<Path>, ) -> Result<(FileMetadata, ResumableUpload), GenaiError>
Uploads a file using chunked transfer to minimize memory usage.
Unlike upload_file, this method streams the file from disk in chunks,
never loading the entire file into memory. This is ideal for large files
(500MB-2GB) or memory-constrained environments.
§Arguments
path- Path to the file to upload
§Returns
Returns a tuple of:
FileMetadata: The uploaded file’s metadataResumableUpload: A handle that can be used to resume if the upload is interrupted
§Memory Usage
This method uses approximately 8MB of memory for buffering, regardless of the file size. A 2GB file uses the same memory as a 10MB file.
§Errors
Returns an error if:
- The file cannot be read
- The MIME type cannot be determined
- The upload fails
§Example
use genai_rs::{Client, Content};
let client = Client::new("api-key".to_string());
// Upload a large video file without loading it all into memory
let (file, _upload_handle) = client.upload_file_chunked("large_video.mp4").await?;
println!("Uploaded: {} -> {}", file.name, file.uri);
// Use in interaction
let response = client.interaction()
.with_model("gemini-3-flash-preview")
.with_content(vec![
Content::text("Describe this video"),
Content::from_file(&file),
])
.create()
.await?;Sourcepub async fn upload_file_chunked_with_mime(
&self,
path: impl AsRef<Path>,
mime_type: &str,
) -> Result<(FileMetadata, ResumableUpload), GenaiError>
pub async fn upload_file_chunked_with_mime( &self, path: impl AsRef<Path>, mime_type: &str, ) -> Result<(FileMetadata, ResumableUpload), GenaiError>
Uploads a file using chunked transfer with an explicit MIME type.
Use this when automatic MIME type detection isn’t suitable.
§Arguments
path- Path to the file to uploadmime_type- MIME type of the file (e.g., “video/mp4”)
§Example
use genai_rs::Client;
let client = Client::new("api-key".to_string());
let (file, _) = client.upload_file_chunked_with_mime(
"data.bin",
"application/octet-stream"
).await?;Sourcepub async fn upload_file_chunked_with_options(
&self,
path: impl AsRef<Path>,
mime_type: &str,
chunk_size: usize,
) -> Result<(FileMetadata, ResumableUpload), GenaiError>
pub async fn upload_file_chunked_with_options( &self, path: impl AsRef<Path>, mime_type: &str, chunk_size: usize, ) -> Result<(FileMetadata, ResumableUpload), GenaiError>
Uploads a file using chunked transfer with a custom chunk size.
This is the same as upload_file_chunked_with_mime but allows
specifying the chunk size for streaming. Larger chunks are more
efficient for fast networks, while smaller chunks use less memory.
§Arguments
path- Path to the file to uploadmime_type- MIME type of the filechunk_size- Size of chunks to stream in bytes (default: 8MB)
§Example
use genai_rs::Client;
let client = Client::new("api-key".to_string());
// Use 16MB chunks for faster upload on a fast network
let chunk_size = 16 * 1024 * 1024;
let (file, _) = client.upload_file_chunked_with_options(
"large_video.mp4",
"video/mp4",
chunk_size
).await?;Sourcepub async fn wait_for_file_ready(
&self,
file: &FileMetadata,
poll_interval: Duration,
timeout: Duration,
) -> Result<FileMetadata, GenaiError>
pub async fn wait_for_file_ready( &self, file: &FileMetadata, poll_interval: Duration, timeout: Duration, ) -> Result<FileMetadata, GenaiError>
Waits for a file to finish processing.
Some files (especially videos) require processing before they can be used. This method polls the file status until it becomes active or fails.
§Arguments
file- The file metadata to wait forpoll_interval- How often to check the statustimeout- Maximum time to wait
§Returns
Returns the updated file metadata when processing completes.
§Errors
Returns an error if:
- The file processing fails
- The timeout is exceeded
§Example
use genai_rs::Client;
use std::time::Duration;
let client = Client::new("api-key".to_string());
let file = client.upload_file("large_video.mp4").await?;
// Wait for processing to complete
let ready_file = client.wait_for_file_ready(
&file,
Duration::from_secs(2),
Duration::from_secs(120)
).await?;
println!("File ready: {}", ready_file.uri);Trait Implementations§
Auto Trait Implementations§
impl Freeze for Client
impl !RefUnwindSafe for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl !UnwindSafe for Client
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the foreground set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red() and
green(), which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg():
use yansi::{Paint, Color};
painted.fg(Color::White);Set foreground color to white using white().
use yansi::Paint;
painted.white();Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the background set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red() and
on_green(), which have the same functionality but
are pithier.
§Example
Set background color to red using fg():
use yansi::{Paint, Color};
painted.bg(Color::Red);Set background color to red using on_red().
use yansi::Paint;
painted.on_red();Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute value.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold() and
underline(), which have the same functionality
but are pithier.
§Example
Make text bold using attr():
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);Make text bold using using bold().
use yansi::Paint;
painted.bold();Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi Quirk value.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask() and
wrap(), which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk():
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);Enable wrapping using wrap().
use yansi::Paint;
painted.wrap();Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted only when both stdout and stderr are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);