gemini-rust

Library Listed

Rust client for Google Gemini API

Checked · Sources

Downloads
6,041
Dependents
5
Stars
79
Forks
27
Contributors
16
Commits
221
Latest release
2.1.0 ·

About

From the project README ·

A comprehensive Rust client library for Google's Gemini API.

Read the full README

✨ Features

  • 🤝 Interactions API (Recommended) - Unified interface for models and agents with server-side state, observable execution steps, and background execution
  • 🤖 Managed Agents - Built-in Deep Research and Antigravity agents with sandbox environments
  • 🔄 Background Execution - Long-running interactions with polling and webhook callbacks
  • 🚀 Complete Gemini API Implementation - Full support for all Gemini API endpoints
  • 🛠️ Function Calling & Tools - Custom functions, Google Search, and Google Maps integration with OpenAPI schema support
  • 🗺️ Google Maps Grounding - Location-aware responses with Google Maps data and widget support
  • 📦 Batch Processing - Efficient batch content generation and embedding
  • 💾 Content Caching - Cache system instructions and conversation history for cost optimization
  • 🔄 Streaming Responses - Real-time streaming of generated content via SSE step lifecycle events
  • 🧠 Thinking Mode - Support for Gemini 2.5+ thinking capabilities
  • 🚀 Gemini 3 Pro - Code execution, advanced thinking levels, and media resolution control
  • 🔢 Token Count API - Pre-calculate token usage for cost optimization
  • 🎯 Safety Settings - Customize content moderation and safety filters
  • 📁 File Handles - Efficient file reference without re-encoding large files
  • 🍌 Image Generation - Text-to-image generation and image editing capabilities
  • 🎤 Speech Generation - Text-to-speech with single and multi-speaker support
  • 🖼️ Multimodal Support - Images and binary data processing
  • 📊 Text Embeddings - Advanced embedding generation with multiple task types
  • 🔍 File Search - Retrieval Augmented Generation (RAG) with semantic document search
  • ⚙️ Highly Configurable - Custom models, endpoints, and generation parameters with HTTP client builder
  • 🔒 Type Safe - Comprehensive type definitions with full serde support
  • ⚡ Async/Await - Built on tokio for high-performance async operations
  • 🔍 Comprehensive Tracing - Built-in structured logging and telemetry with tracing for observability

📦 Installation

Add this to your Cargo.toml:

[dependencies]
gemini-rust = "2.0.0"

🚀 Quick Start

Interactions API (Recommended)

The Interactions API is the simplest and best way to use Gemini models and agents. It provides server-side state management, observable execution steps, background execution, and unified support for models and agents.

use gemini_rust::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GEMINI_API_KEY")?;
    let client = Gemini::new(api_key)?;

    // Basic text generation
    let interaction = client
        .create_interaction()
        .with_model("gemini-3.7-flash")
        .with_text("Hello! What is AI?")
        .execute()
        .await?;

    println!("{}", interaction.output_text());

    // Multi-turn with server-side state
    let interaction2 = client
        .create_interaction()
        .with_model("gemini-3.7-flash")
        .with_text("Give me 3 examples")
        .with_previous_interaction(interaction.id().unwrap())
        .execute()
        .await?;

    println!("{}", interaction2.output_text());

    Ok(())
}

Key features:

  • Server-side state — previous_interaction_id for multi-turn conversations
  • Background execution — .with_background() + polling
  • Managed agents — Deep Research, Antigravity
  • Observable steps — thoughts, function calls, tool usage as typed steps
  • SSE streaming — step lifecycle events (start/delta/stop)
  • Structured output — JSON schema via .with_json_schema()

See the interaction_*.rs examples for complete coverage of every feature.

Legacy generateContent API

The original generateContent API is still available but deprecated. New code should use the Interactions API.

🔁 Migration Guide: generateContent → Interactions API

Paradigm Shift

The Interactions API introduces a fundamentally different request/response model:

generateContent (Legacy)                  Interactions API (Recommended)

Contents (messages)  →  Candidates        Interaction (input)  →  Steps (typed actions)
AspectgenerateContent (Legacy)Interactions API (Recommended)
Requestcontents: Vec<Content> (role + parts)input: string | Content[] | Step[]
Responsecandidates: Vec<Candidate> (parts)steps: Vec<Step> (typed enum)
Multi-turn stateClient manages full historyServer-side previous_interaction_id
StreamingSSE chunks of GenerationResponseSSE step lifecycle events (step.start/delta/stop)
Function callingPart::FunctionCall / Part::FunctionResponseStep::FunctionCall / Step::FunctionResult
Background executionNot supportedbackground=true + polling or webhook
Managed agentsNot supportedDeep Research, Antigravity
Sandbox environmentsNot supportedenvironment: "remote"
Service tiersNot supportedflex, standard, priority
Side-by-Side Code Comparison
Basic Text Generation
// ── Legacy generateContent ──
let response = client.generate_content(
    GenerateContentRequest::builder()
        .model("gemini-3.7-flash")
        .contents(vec![Message::new_user("What is AI?")])
        .build()
).await?;
println!("{}", response.candidates[0].content.parts[0].text);

// ── Interactions API ──
let interaction = client.create_interaction()
    .with_model("gemini-3.7-flash")
    .with_text("What is AI?")
    .execute()
    .await?;
println!("{}", interaction.output_text());
Multi-Turn Conversation
// ── Legacy: manually resend entire history ──
let response2 = client.generate_content(
    GenerateContentRequest::builder()
        .model("gemini-3.7-flash")
        .contents(vec![
            Message::new_user("What is AI?"),
            Message::new_model(&response.candidates[0].content.parts[0].text),
            Message::new_user("Give me 3 examples"),
        ])
        .build()
).await?;

// ── Interactions: server-side state via previous_interaction_id ──
let interaction2 = client.create_interaction()
    .with_model("gemini-3.7-flash")
    .with_text("Give me 3 examples")
    .with_previous_interaction(interaction.id().unwrap())
    .execute()
    .await?;
Streaming
// ── Legacy: SSE chunks of GenerationResponse ──
use gemini_rust::prelude::*;
let mut stream = client.generate_content_stream(request).await?;
while let Some(chunk) = stream.next().await {
    let chunk = chunk?;
    if let Some(part) = chunk.candidates[0].content.parts.first() {
        print!("{}", part.text);
    }
}

// ── Interactions: SSE step lifecycle events ──
let mut stream = client.create_interaction_stream(
    client.create_interaction()
        .with_model("gemini-3.7-flash")
        .with_text("Write a haiku about Rust")
).await?;
while let Some(event) = stream.next().await {
    let event = event?;
    match event {
        InteractionEvent::StepStart(step) => { /* step began */ }
        InteractionEvent::StepDelta(delta) => { /* incremental text */ }
        InteractionEvent::StepStop(step) => { /* step finished */ }
        InteractionEvent::InteractionCompleted(i) => { /* done */ }
        _ => {}
    }
}
Feature Availability

New in Interactions API (not in generateContent):

  • Server-side conversation state (previous_interaction_id)
  • Background execution with polling or webhooks
  • Managed agents (Deep Research, Antigravity)
  • Remote sandbox environments
  • Observable execution steps (thoughts, tool calls, code execution)
  • Service tiers (flex, standard, priority)
  • Webhook callbacks

Only in generateContent (not yet in Interactions API):

  • Batch API
  • Explicit content caching
  • Custom safety settings
  • Video metadata (clipping, frame rate)
  • Automatic function calling
Type Mapping
Legacy TypeInteractions TypeNotes
Content / PartInteractionContentType-tagged polymorphic
CandidateStep::ModelOutputFilter steps for ModelOutput variant
Part::TextInteractionContent::Text
Part::InlineDataInteractionContent::Image / Audio / VideoTyped per media
Part::FunctionCallStep::FunctionCallNow a top-level step, not a Part
Part::FunctionResponseStep::FunctionResultProvide tool results back
GenerationConfigInteractionGenerationConfigShared subset of fields
ToolInteractionToolType-tagged polymorphic
Migration Checklist
  1. Start with simple text generation — swap generate_content() for create_interaction().execute()
  2. Replace multi-turn logic — use with_previous_interaction() instead of rebuilding history
  3. Update response parsing — use interaction.output_text() instead of response.candidates[0]...
  4. Switch streaming — handle InteractionEvent variants instead of raw chunks
  5. Map tools — convert Tool to InteractionTool (function, google_search, code_execution, etc.)
  6. Explore new features — try with_background(), with_agent(), or with_environment()
Basic Content Generation

Get started with simple text generation, system prompts, and conversations. See basic_generation.rs for complete examples including simple messages, system prompts, and multi-turn conversations.

Streaming Responses

Enable real-time content streaming for interactive applications. See basic_streaming.rs for examples of processing content as it's generated with immediate display.

Google Maps Grounding

Add location-aware capabilities to your applications with Google Maps integration. See simple_maps_example.rs for basic usage and google_maps_grounding.rs for comprehensive examples.

Token Count API

Calculate token usage before making generation requests for cost estimation and optimization. See count_tokens.rs.

Safety Settings

Customize content moderation with granular control over different harm categories and block thresholds. See safety_settings.rs.

Gemini 3 Pro

Access the latest model features including code execution and advanced thinking levels. See gemini_3_code_execution.rs for code execution and gemini_3_thinking_and_media.rs for thinking levels.

🛠️ Key Features

The library provides comprehensive access to all Gemini 2.5 capabilities through an intuitive Rust API:

🧠 Thinking Mode (Gemini 2.5)

Advanced reasoning capabilities with thought process visibility and custom thinking budgets. See thinking_basic.rs and thinking_advanced.rs.

🛠️ Function Calling & Tools
  • Custom function declarations with OpenAPI schema support (using schemars)
  • Google Search integration for real-time information
  • Google Maps grounding for location-aware responses
  • Type-safe function definitions with automatic schema generation
  • See tools.rs, complex_function.rs, and google_maps_grounding.rs
🗺️ Google Maps Grounding
  • Location-Aware Responses: Access Google Maps data for geographically specific queries
  • Widget Support: Generate context tokens for interactive Google Maps widgets
  • Grounding Sources: Access citation information for all Maps data used in responses
  • Easy Integration: Simple API with location context configuration
  • See simple_maps_example.rs and advanced_maps_configuration.rs
🎨 Multimodal Generation
  • Image Generation: Nano Banana (Flash) and Pro (Gemini 3) Text-to-image with detailed thinking and follow up editing capabilities
  • Speech Generation: Text-to-speech with single and multi-speaker support
  • Image Processing: Analyze images, videos, and binary data
  • See image_generation.rs and multi_speaker_tts.rs
📦 Batch Processing

Efficient processing of multiple requests with automatic file handling for large jobs. See batch_generate.rs.

💾 Content Caching

Cache system instructions and conversation history to reduce costs and improve performance. See cache_basic.rs.

📊 Text Embeddings

Advanced embedding generation with multiple task types for document retrieval and semantic search. See embedding.rs.

🔍 File Search (RAG)
  • Semantic Document Search: Upload documents and query them with natural language
  • Automatic Chunking: Documents are automatically split, embedded, and indexed
  • Custom Metadata: Filter searches using metadata tags (e.g., category = "api-docs")
  • Grounding Citations: Get source references for model responses
  • Multiple Upload Methods: Direct upload or import from Files API
  • Persistent Storage: Documents persist indefinitely until deleted
  • See file_search_basic.rs, file_search_metadata.rs, and file_search_import.rs
🔄 Streaming Responses

Real-time streaming of generated content for interactive applications. See streaming.rs.

⚙️ Highly Configurable
🔍 Observability

Built-in structured logging and telemetry with tracing for comprehensive monitoring and debugging.

🔢 Token Count API

Pre-calculate token usage for cost estimation and optimization. Calculate tokens for your requests before executing them. See count_tokens.rs.

🎯 Safety Settings

Customize content moderation with granular control over different harm categories (Hate Speech, Dangerous Content, etc.) and block thresholds (Block None, Low, Medium, High). See safety_settings.rs.

🚀 Gemini 3 Pro
  • Code Execution: Generate and execute Python code for mathematical calculations, data analysis, and computational tasks
  • Thinking Levels: Choose Low for faster responses or High for deeper analysis
  • Media Resolution: Fine-grained control over image and PDF processing quality
  • See gemini_3_code_execution.rs and gemini_3_thinking_and_media.rs
📁 File Handles

Efficiently reference previously uploaded files without re-encoding. Upload files once and reference them multiple times, reducing data transfer. Supports PDFs, images, and other binary formats. See file_input.rs and files_usage.rs.

🔧 Configuration

Custom Models

Configure different Gemini models including Flash, Pro, Lite, and custom models. See custom_models.rs for examples of all model configuration options including convenience methods, enum variants, and custom model strings.

Custom Base URL

Use custom API endpoints and configurations. See custom_base_url.rs for examples of configuring custom endpoints with different models.

Configurable HTTP Client Builder

For advanced HTTP configuration (timeouts, proxies, custom headers), use the builder pattern. See http_client_builder.rs for a complete example with custom timeouts, user agents, connection pooling, and proxy configuration.

🔍 Tracing and Telemetry

The library is instrumented with the tracing crate to provide detailed telemetry data for monitoring and debugging. This allows you to gain deep insights into the library's performance and behavior.

Key tracing features include:

  • HTTP Request Tracing: Captures detailed information about every API call, including HTTP method, URL, and response status, to help diagnose network-related issues
  • Token Usage Monitoring: Records the number of prompt, candidate, and total tokens for each generation request, enabling cost analysis and optimization
  • Structured Logging: Emits traces as structured events, compatible with modern log aggregation platforms like Elasticsearch, Datadog, and Honeycomb, allowing for powerful querying and visualization
  • Performance Metrics: Provides timing information for each API request, allowing you to identify and address performance bottlenecks

To use these features, you will need to integrate a tracing subscriber into your application. See tracing_telemetry.rs for comprehensive examples including basic console logging, structured logging for production, and environment-based log level filtering.

📚 Examples

The repository includes 30+ comprehensive examples demonstrating all features. See examples/README.md for detailed information.

Quick Start Examples
Interactions API Examples

Run any example:

GEMINI_API_KEY="your-api-key" cargo run --example basic_generation

🔑 API Key Setup

Get your API key from Google AI Studio and set it as an environment variable:

export GEMINI_API_KEY="your-api-key-here"

🚦 Supported Models

Standard Models (Both APIs)
  • Gemini 3.7 Flash - Latest and most capable Flash model (default) - Model::Gemini37Flash
  • Gemini 3.6 Flash - Previous-generation Flash model - Model::Gemini36Flash
  • Gemini 3.5 Flash - Legacy Flash model - Model::Gemini35Flash
  • Gemini 3.5 Flash-Lite - Fastest, most cost-effective 3.5 model - Model::Gemini35FlashLite
  • Gemini 3.1 Flash-Lite - Cost-efficient multimodal model - Model::Gemini31FlashLite
  • Gemini 3.1 Pro - Current Pro model with advanced thinking and agentic capabilities (Preview) - Model::Gemini31Pro
  • Gemini 3 Flash - Flash model with thinking levels (Minimal, Low, Medium, High) (Preview) - Model::Gemini3Flash
  • Gemini 2.5 Flash - Previous generation, unavailable to newly created API keys - Model::Gemini25Flash
  • Gemini 2.5 Flash Lite - Lightweight model - Model::Gemini25FlashLite
  • Gemini 2.5 Pro - Advanced model with thinking capabilities - Model::Gemini25Pro
Image Generation
  • Gemini 3.1 Flash Image - Nano Banana 2, high-efficiency image generation - Model::Gemini31FlashImage
  • Gemini 3.1 Flash-Lite Image - Nano Banana 2 Lite, ultra-low latency - Model::Gemini31FlashLiteImage
  • Gemini 3 Pro Image - Nano Banana Pro, studio-quality generation - Model::Gemini3ProImage
  • Gemini 2.5 Flash Image - Nano Banana (shutting down October 2, 2026) - Model::Gemini25FlashImage
Speech, Video, and Tools
  • Gemini 3.1 Flash TTS - Low-latency speech generation - Model::Gemini31FlashTts (Preview)
  • Gemini 2.5 Flash TTS / 2.5 Pro TTS - Text-to-speech - Model::Gemini25FlashTts / Model::Gemini25ProTts
  • Gemini Omni Flash - Conversational video generation and editing - Model::GeminiOmniFlash
  • Gemini 2.5 Computer Use - UI automation model - Model::Gemini25ComputerUse
Embeddings
  • Gemini Embedding 2 - Multimodal embeddings (text, images, video, audio, PDFs) - Model::GeminiEmbedding2
  • Gemini Embedding 001 - Text embeddings for search and RAG - Model::GeminiEmbedding001
Deprecated
  • Gemini 3 Pro - Model::Gemini3Pro (shut down on March 9, 2026; use Model::Gemini31Pro)
  • Text Embedding 004 - Model::TextEmbedding004 (shut down on January 14, 2026; use Model::GeminiEmbedding2)
  • Custom models - Use Model::Custom(String) or string literals for any other model
Managed Agents (Interactions API only)
  • Deep Research - Multi-step research agent with report generation - AgentConfig::DeepResearch or .with_agent("deepresearch-2.5")
  • Antigravity - Code-writing agent with remote sandbox - .with_agent("antigravity-preview-05-2026")

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

For guidelines on developing agents and applications, see the Agent Development Guide.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Google for providing the Gemini API
  • The Rust community for excellent async and HTTP libraries
  • Special thanks to @npatsakula for major contributions that made this project more complete
  • All contributors who have helped improve this library
Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
None found
  • No native code found
Python bindings
No Python binding crate found
License
MIT

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

gemini-rust beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
gemini-rust This page Listed

Rust client for Google Gemini API

6,041 downloads over 30 days 5 79 2.1.0 GPU support unknown No native code found MIT
rust-genai Featured

Multi-AI Providers Library for Rust. (OpenAI, Gemini, Anthropic, DeepSeek, Ollama, OMLX, AWS Bedrock, Vertex, Xai, Groq, Kimi, GLM and many more)

118,643 downloads over 30 days 81 938 0.7.3 GPU support unknown No native code found Apache-2.0 OR MIT
ollama-rs Featured

A Rust library for interacting with the Ollama API

45,579 downloads over 30 days 68 1,061 0.3.6 GPU support unknown No native code found MIT

OpenAI API client library for Rust (unofficial)

46,400 downloads over 30 days 33 485 10.0.2 GPU support unknown No native code found MIT

A Rust SDK for the Google Gemini API

2,207 downloads over 30 days 2 13 0.10.0 GPU support unknown No native code found MIT
mistralai-client-rs Listed Dormant

Mistral AI API client library for Rust (unofficial).

518 downloads over 30 days 4 48 0.14.0 GPU support unknown No native code found Apache-2.0
blazr App Listed

Inference server for LLMs, speech and embeddings: OpenAI-compatible routes with streaming, plus speech synthesis (TTS) and transcription (ASR). Serves Llama, Mistral, Qwen, Mamba2, MLA+MoE and hybrid models from SafeTensors, AWQ, GPTQ and GGUF.

8 binary downloads per release Not applicable 7 0.7.1 CUDA, WebGPU Binds native code: ring (feature distributed) Apache-2.0
Why ListedNo archive, New or Featured rule places it, so it is Listed.

What it lacks for Featured

  • It has 3 active dependents and 3 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days. The repository route reads 79 stars, 27 forks and 16 contributors. It needs 4,539 stars, 434 forks and 79 contributors together.

What else the check found

  • The last activity is on 5 Sep 2026, 65 days ago. The rules expect an update within 365 days. Dormancy rule

Exact rules: Listed, Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 2.1.0 base 200, raised to the 365-day floor: E = 365 days
  • dormancy: last activity 2026-09-05, 65 days ago, E = 365: active
  • featured: not featured: active_users 3 < 11 and new_adopters 3 < 9 and repository route stars 79 (needs 4539), forks 27 (needs 434), contributors 16 (needs 79)
  • listed: listed: no archive, new or featured rule applies

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption3 active dependents, 3 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents3crates.io database dumpYes
New dependents (365 days)3crates.io database dumpYes
Peak active dependents3crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 2 months ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-09-05GitHub repositoryYes
Latest release2026-09-05crates.io database dumpYes
First release2025-03-25crates.io database dumpYes
Latest version2.1.0crates.io database dumpYes
Days the oldest outside issue waits for a reply291GitHub repositoryYes
Maintainer replies over 365 days29GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution23 releases, 6,041 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases23crates.io database dumpYes
Downloads over 30 days6041crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository79 stars, 27 forks, 16 contributors, 221 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars79GitHub repositoryYes — one part of the repository route
GitHub forks27GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account16GitHub contributorsYes — one part of the repository route
Commits on the default branch221GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseMITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly5crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.