### Basic Text Generation Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md This is the best starting point for beginners to understand simple content generation. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Write a short story about a robot learning to love."; let response = client.generate_content(prompt).await?; println!("{}", response.text()); Ok(()) } ``` -------------------------------- ### Cache Setup and Usage Example Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/configuration.md Demonstrates how to create a cached content request with a system instruction and TTL, and how to use the cached content in a subsequent generation request. ```rust let cached = client .create_cache() .with_system_instruction("You are a helpful assistant") .with_ttl(Duration::from_secs(3600)) .execute() .await?; // Use in future requests let response = client .generate_content() .with_cached_content(&cached) .with_user_message("Remember my instructions and answer this...") .execute() .await?; ``` -------------------------------- ### Run a Gemini Rust Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md This command demonstrates how to run a basic generation example using the Gemini Rust library. Ensure you have set your GEMINI_API_KEY environment variable. ```bash GEMINI_API_KEY="your-api-key" cargo run --example basic_generation ``` -------------------------------- ### Logging Examples: Batch and Error Source: https://github.com/flachesis/gemini-rust/blob/main/AGENTS.md Demonstrates logging a batch start event with custom fields and an error event with an associated error and model name. ```rust info!(batch_name = "my-batch", requests.count = 10, "batch started"); error!(error = %err, model = "gemini-2.5-flash", "generation failed"); ``` -------------------------------- ### Upload File and Get Handle Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/file-operations.md This example demonstrates reading a file from the local filesystem, uploading it using the `FileBuilder`, and then printing the name of the uploaded file using its handle. Ensure the file exists at the specified path. ```rust let file_bytes = std::fs::read("document.pdf")?; let file_handle = client .upload_file(file_bytes) .display_name("My Document") .upload() .await?; println!("File uploaded: {}", file_handle.name()); ``` -------------------------------- ### Batch Content Generation Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Shows how to perform batch content generation for multiple requests efficiently. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompts = vec![ "Generate a short poem about rain.", "Write a haiku about the moon.", "Create a tagline for a coffee shop.", ]; // Assuming a method for batch generation exists. let responses = client.generate_content_batch(prompts).await?; for (i, response) in responses.iter().enumerate() { println!("Batch Response {}:\n{}", i + 1, response.text()); } Ok(()) } ``` -------------------------------- ### Basic Streaming Response Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Demonstrates how to handle simple streaming responses for real-time content display. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Describe the process of photosynthesis in a way a child can understand."; let mut stream = client.generate_content_stream(prompt).await?; while let Some(chunk) = stream.next().await { print!("{}", chunk.text()); } println!(); Ok(()) } ``` -------------------------------- ### Simple Text Generation and Function Calling Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md A comprehensive example showcasing basic text generation alongside function calling capabilities. ```rust use gemini_rust::GeminiClient; use serde::Deserialize; #[derive(Deserialize, Debug)] struct GetWeatherArgs { location: String, unit: Option, } #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "What's the weather like in Boston?"; let response = client.generate_content(prompt).await?; println!("{}", response.text()); // Example of how to potentially parse function calls if the model returns them // This part would require more sophisticated handling based on the actual response structure // For demonstration, we'll just print the text response. Ok(()) } ``` -------------------------------- ### Tracing and Telemetry Setup (Rust) Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Provides a comprehensive setup for tracing and telemetry, enhancing observability and monitoring of API interactions. ```rust tracing_telemetry.rs ``` -------------------------------- ### Full Instrumentation Pattern Example Source: https://github.com/flachesis/gemini-rust/blob/main/AGENTS.md A comprehensive example of instrumentation fields for various aspects of a request, including batch, file, mime type, and display name. ```rust #[instrument(skip_all, fields( model, messages.parts.count = request.contents.len(), tools.present = request.tools.is_some(), system.instruction.present = request.system_instruction.is_some(), cached.content.present = request.cached_content.is_some(), task.type = request.task_type.as_ref().map(|t| format!(‘{:?}‘, t)), task.title = request.title, task.output.dimensionality = request.output_dimensionality, batch.size = request.requests.len(), batch.display_name = request.batch.display_name, operation.name = name, page.size = page_size, page.token.present = page_token.is_some(), file.name = name, file.size = file_bytes.len(), mime.type = mime_type.to_string(), file.display_name = display_name.as_deref(), ))] ``` -------------------------------- ### Custom Base URL Configuration Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Configure custom API endpoints and model configurations. This example demonstrates setting a custom base URL for API requests. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let custom_url = "https://your-gemini-endpoint.com/v1"; gemini.set_base_url(custom_url); gemini.set_model("gemini-1.5-pro-latest"); // Ensure model is compatible with custom URL let prompt = "Request to a custom endpoint."; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Custom Models Configuration Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Configure different Gemini models including Flash, Pro, Lite, and custom models. This example shows how to specify model names. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); // Example: Using Gemini 1.5 Flash gemini.set_model("gemini-1.5-flash-latest"); let prompt = "A quick summary of the topic."; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Advanced Content Generation Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Demonstrates advanced content generation with comprehensive parameter configuration. ```rust use gemini_rust::GeminiClient; use gemini_rust::GenerationConfig; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Write a poem about the stars."; let generation_config = GenerationConfig { temperature: Some(0.7), max_output_tokens: Some(150), top_p: Some(0.9), top_k: Some(40), ..Default::default() }; let response = client.generate_content_with_config(prompt, generation_config).await?; println!("{}", response.text()); Ok(()) } ``` -------------------------------- ### Image and Media Handling (Rust) Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Examples for working with multimodal content, including images and videos. Requires setting the GEMINI_API_KEY environment variable. ```bash GEMINI_API_KEY="your-api-key" cargo run --example blob ``` ```bash GEMINI_API_KEY="your-api-key" cargo run --example image_generation ``` -------------------------------- ### Basic Text-to-Image Generation Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md A simple example demonstrating basic text-to-image generation capabilities. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "A futuristic cityscape at sunset, digital art"; // Assuming a method for image generation exists. let response = client.generate_image(prompt).await?; // The response would typically contain image data or a URL. println!("Image generation response (URL or data):\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Google Search Functionality with cURL Equivalents Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md This example demonstrates Google Search functionality and provides equivalent cURL commands for reference. ```rust use gemini_rust::GeminiClient; use gemini_rust::ToolConfig; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let google_search_tool = ToolConfig::FunctionDeclaration(gemini_rust::FunctionDeclaration { name: "google_search".to_string(), description: "Perform a Google search and return relevant snippets.".to_string(), parameters: serde_json::json!({ "type": "object", "properties": { "query": { "type": "string", "description": "The search query." } }, "required": ["query"] }), }); let tools = vec![google_search_tool]; let prompt = "What is the capital of France? Provide the answer as if it were a cURL command output."; let response = client.generate_content_with_tools(prompt, tools).await?; println!("Response with cURL equivalent concept:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Basic Batch Processing Example Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/batch-builder.md Demonstrates how to perform basic batch processing by creating multiple generation requests, submitting them, and monitoring their status and results. ```APIDOC ## Usage Examples ### Basic Batch Processing ```rust use gemini_rust::prelude::*; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let client = Gemini::new(std::env::var("GEMINI_API_KEY")?)?; // Create requests let requests = vec![ client.generate_content() .with_user_message("Count to 10") .build(), client.generate_content() .with_user_message("List 5 colors") .build(), client.generate_content() .with_user_message("Explain photosynthesis") .build(), ]; // Submit batch let batch_handle = client .batch_generate_content() .with_name("Example Batch".to_string()) .with_requests(requests) .execute() .await?; println!("Batch submitted: {}", batch_handle.name()); // Monitor completion loop { match batch_handle.status().await? { BatchStatus::Succeeded { results } => { for (i, item) in results.iter().enumerate() { match &item.response { Ok(response) => println!("Result {}: {}", i, response.text()), Err(e) => println!("Result {} error: {}", i, e.message), } } break; } BatchStatus::Running { completed_count, total_count, .. } => { println!("Progress: {}/{}", completed_count, total_count); tokio::time::sleep(Duration::from_secs(10)).await; } _ => break, } } Ok(()) } ``` ``` -------------------------------- ### Image Generation Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Shows how to generate images using the Nano Banana (Flash) or Pro (Gemini 3) models. Requires appropriate model configuration. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let prompt = "A futuristic cityscape at sunset"; let response = gemini.generate_content(prompt).await?; // The response will contain a URL or data for the generated image println!("{}", response); Ok(()) } ``` -------------------------------- ### Basic Thinking Mode Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Demonstrates the basic usage of thinking mode for step-by-step reasoning capabilities. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Solve the following math problem: 5 + 8 * 3"; // Assuming 'with_thinking_mode' is a method to enable this feature. // The exact API might differ based on library implementation. let response = client.generate_content_with_thinking(prompt).await?; println!("Thinking mode response:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Simple Thought Signature Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Illustrates basic examples of using thought signatures for structured reasoning output. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Think step-by-step about how to bake a cake."; // Assuming 'with_thought_signature' enables this feature. let response = client.generate_content_with_thought_signature(prompt).await?; println!("Simple thought signature response:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Configure Tools with ToolConfig Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/tools-functions.md Initialize and apply a `ToolConfig` to the client. This example enables function calling in `Auto` mode and enables the Google Maps widget. ```rust let tool_config = ToolConfig { function_calling_config: Some(FunctionCallingConfig { mode: FunctionCallingMode::Auto, }), google_maps_config: Some(GoogleMapsConfig { enable_widget: Some(true), }), }; let response = client .generate_content() .with_tool_config(tool_config) .with_user_message("Use your tools to answer this") .execute() .await?; ``` -------------------------------- ### Simple Google Maps Grounding Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Demonstrates basic integration with Google Maps for location-aware responses. Ensure Google Maps API is configured. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let prompt = "What's the weather like in San Francisco?"; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Custom Generation Parameters Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Configure custom generation parameters such as temperature, token limits, and top-k/top-p sampling. ```rust use gemini_rust::GeminiClient; use gemini_rust::GenerationConfig; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Write a short, creative story."; let generation_config = GenerationConfig { temperature: Some(0.9), // Higher temperature for more creativity max_output_tokens: Some(200), top_p: Some(0.95), top_k: Some(40), ..Default::default() }; let response = client.generate_content_with_config(prompt, generation_config).await?; println!("Creative story:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Advanced Google Maps Configuration Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Illustrates advanced configuration options for Google Maps grounding, allowing for more specific location contexts and data retrieval. ```rust use gemini_rust::gemini::Gemini; use gemini_rust::gemini::maps::MapsGrounding; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let maps_grounding = MapsGrounding::new("YOUR_GOOGLE_MAPS_API_KEY"); gemini.set_maps_grounding(maps_grounding); let prompt = "Find restaurants near the Eiffel Tower."; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Full File Upload, Usage, and Cleanup Workflow Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/file-operations.md A complete example demonstrating reading a PDF, uploading it, using it in two separate content generation requests, and then deleting the uploaded file. Requires 'manual.pdf' to exist. ```rust #[tokio::main] async fn main() -> Result<(), Box> { let client = Gemini::new(std::env::var("GEMINI_API_KEY")?)?; // Upload file let pdf_bytes = std::fs::read("manual.pdf")?; let file = client .upload_file(pdf_bytes) .display_name("User Manual") .upload() .await?; println!("Uploaded: {}", file.name()); // Use in multiple requests let response1 = client .generate_content() .with_user_message_and_file("What is the overview?", &file)? .execute() .await?; let response2 = client .generate_content() .with_user_message_and_file("Explain chapter 3", &file)? .execute() .await?; // Clean up file.delete().await?; Ok(()) } ``` -------------------------------- ### Streaming Responses for Interactive Applications Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md This example shows how to implement real-time streaming responses, suitable for interactive applications. ```rust use gemini_rust::GeminiClient; use futures::StreamExt; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Explain the concept of recursion."; let mut stream = client.generate_content_stream(prompt).await?; println!("Streaming response:"); while let Some(chunk) = stream.next().await { match chunk { Ok(response_part) => { print!("{}", response_part.text()); } Err(e) => { eprintln!("Error receiving stream chunk: {}", e); break; } } } println!(); Ok(()) } ``` -------------------------------- ### Generation Configuration Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Customize detailed generation parameters such as temperature, token limits, and stop sequences. This allows fine-tuning of the model's output. ```rust use gemini_rust::gemini::Gemini; use gemini_rust::gemini::generation::{GenerationConfig, ResponseMimeType}; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let generation_config = GenerationConfig { temperature: Some(0.7), max_output_tokens: Some(1024), response_mime_type: Some(ResponseMimeType::Text), ..Default::default() }; gemini.set_generation_config(generation_config); let prompt = "Write a short story about a space explorer."; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Multi-Speaker Text-to-Speech Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Demonstrates generating speech with support for multiple speakers. Ensure TTS models are available and configured. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let prompt = "Hello, this is a test of multi-speaker TTS."; // Specify speaker if needed, otherwise a default will be used let response = gemini.generate_content(prompt).await?; // The response will contain audio data or a URL println!("{}", response); Ok(()) } ``` -------------------------------- ### Advanced HTTP Client Configuration (Rust) Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Illustrates advanced HTTP client setup, including timeouts, proxies, and connection pooling for robust network communication. ```rust http_client_builder.rs ``` -------------------------------- ### Simple API Connectivity Test Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md A straightforward example to test basic API connectivity with the Gemini service. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); // A simple prompt to check if the API is reachable and responding. let prompt = "Hello"; match client.generate_content(prompt).await { Ok(response) => { println!("API is working! Response: {}", response.text()); } Err(e) => { eprintln!("API test failed: {}", e); } } Ok(()) } ``` -------------------------------- ### Files Usage Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Demonstrates multiple uses of uploaded files within a single session or across different requests. Supports PDFs, images, and other binary formats. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); // Upload multiple files let file1_path = "./image1.jpg"; let file2_path = "./report.pdf"; let file_handle1 = gemini.upload_file(file1_path).await?; let file_handle2 = gemini.upload_file(file2_path).await?; // Use files in a single prompt let prompt = format!( "Compare the content of file {} and file {}.", file_handle1.file_id, file_handle2.file_id ); let response = gemini.generate_content_with_files( prompt, vec![&file_handle1.file_id, &file_handle2.file_id] ).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Streaming Responses Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Implement real-time streaming of generated content for interactive applications. This provides immediate feedback to the user. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let prompt = "Describe a sunset in detail."; let mut stream = gemini.generate_content_stream(prompt).await?; while let Some(chunk) = stream.next().await { print!("{}", chunk?); } println!(); Ok(()) } ``` -------------------------------- ### Gemini 3 Code Execution Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Demonstrates code execution capabilities with Python, including tool integration for Gemini 3 Pro. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Write a Python script to calculate the factorial of 5 and execute it."; // This assumes the Gemini 3 model and the client support code execution. let response = client.generate_content(prompt).await?; println!("Gemini 3 code execution response:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Advanced Image Generation with Detailed Prompts Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Provides an example of advanced image generation using detailed and specific prompts. ```rust use gemini_rust::GeminiClient; use gemini_rust::ImageGenerationConfig; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "A photorealistic portrait of an astronaut floating in space, with Earth visible in the background, dramatic lighting, 8k resolution."; let generation_config = ImageGenerationConfig { // Example parameters for advanced control // aspect_ratio: Some("16:9"), // quality: Some("hd"), ..Default::default() }; // Assuming a method for advanced image generation exists. let response = client.generate_image_with_config(prompt, generation_config).await?; println!("Advanced image generation response:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### File Input Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Efficiently reference previously uploaded files without re-encoding. Upload files once and reference them multiple times, reducing data transfer. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); // Upload a file first let file_path = "./document.pdf"; let file_handle = gemini.upload_file(file_path).await?; // Reference the uploaded file in a subsequent request let prompt = "Summarize the content of the uploaded document."; let response = gemini.generate_content_with_file( prompt, &file_handle.file_id ).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Basic Content Caching Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Implement caching for system instructions and conversation history to reduce costs and improve performance. This requires enabling the cache system. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); // Enable caching gemini.enable_caching(); let prompt = "This is a cached request."; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Large Batch with File Upload Example Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/batch-builder.md Illustrates how to handle very large batches by uploading the requests as a file, which is more efficient for a high volume of requests. ```APIDOC ### Large Batch with File Upload ```rust // For very large batches, upload as file let large_requests = (0..5000) .map(|i| { client.generate_content() .with_user_message(format!("Question {}", i)) .build() }) .collect::>(); let batch_handle = client .batch_generate_content() .with_name("Large Batch".to_string()) .with_requests(large_requests) .execute_as_file() .await?; ``` ``` -------------------------------- ### Custom Base URL Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Configure custom API endpoints and model configurations. This is useful for using private endpoints or specific regional deployments. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let custom_base_url = "https://your-custom-api.example.com/v1"; gemini.set_base_url(custom_base_url); let prompt = "Hello from a custom endpoint!"; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### HTTP Client Builder Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Advanced HTTP configuration including timeouts, proxies, and custom headers using a builder pattern. This provides fine-grained control over network requests. ```rust use gemini_rust::gemini::Gemini; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let http_client = reqwest::Client::builder() .timeout(Duration::from_secs(60)) .proxy(reqwest::Proxy::https("http://your-proxy.example.com:8080").unwrap()) .build()?; gemini.set_http_client(http_client); let prompt = "Testing with a custom HTTP client."; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Gemini 3 Thinking and Media Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Showcases Gemini 3 Pro's thinking levels and media resolution capabilities. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Analyze this image [image data] and describe its content, considering different thinking levels."; // This example assumes multimodal input and configurable thinking levels. // The '[image data]' placeholder would be replaced with actual image data. let response = client.generate_content_with_media_and_thinking(prompt).await?; println!("Gemini 3 thinking and media response:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Build Gemini Client with Multiple Configurations Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/configuration.md Construct the Gemini client by chaining multiple builder methods. This example demonstrates setting both the model and timeout before building the client. ```rust let client = GeminiBuilder::new(api_key) .model(Model::Gemini25Pro) .timeout(Duration::from_secs(120)) .build()?; ``` -------------------------------- ### Token Count API Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Pre-calculate token usage for requests to estimate costs and optimize usage. This API helps in managing token budgets effectively. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let prompt = "This is a sample text to count tokens."; let token_count = gemini.count_tokens(prompt).await?; println!("Token count: {}", token_count); Ok(()) } ``` -------------------------------- ### File Search with Import Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Import documents using the Files API for use in semantic search. This method is suitable for integrating with existing file management systems. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); // Assume file_id is obtained from the Files API let file_id = "your_imported_file_id"; let query = "Summarize the content of the imported file."; let response = gemini.generate_content_with_file( query, file_id ).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Using Gemini 2.5 Pro for Advanced Tasks Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md This example specifically shows how to utilize the Gemini 2.5 Pro model for advanced content generation tasks. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { // Ensure the client is configured or defaults to Gemini 2.5 Pro if available/specified. // The actual model selection might depend on configuration or environment variables. let client = GeminiClient::new(); let prompt = "Summarize the key advancements in AI in the last year."; // Assuming the client defaults to or can be configured for Gemini 2.5 Pro. let response = client.generate_content(prompt).await?; println!("Gemini 2.5 Pro response:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Cost Savings Example: With Caching Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/caching.md Demonstrates the reduced token usage when system instructions are cached and reused across multiple requests, showing significant cost savings. ```plaintext Cache creation: 1,000 tokens (system) Request 1: 100 tokens (query) + small cache overhead = ~150 tokens Request 2: 100 tokens (query) + small cache overhead = ~150 tokens Request 3: 100 tokens (query) + small cache overhead = ~150 tokens Total: ~1,400 tokens (58% savings) ``` -------------------------------- ### Safety Settings Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Customize content moderation with granular control over harm categories and block thresholds. This ensures responsible AI usage. ```rust use gemini_rust::gemini::Gemini; use gemini_rust::gemini::safety::{HarmCategory, HarmBlockThreshold}; use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let mut safety_settings = HashMap::new(); safety_settings.insert(HarmCategory::HateSpeech, HarmBlockThreshold::Medium); safety_settings.insert(HarmCategory::DangerousContent, HarmBlockThreshold::High); gemini.set_safety_settings(safety_settings); let prompt = "Generate content that might be flagged."; let response = gemini.generate_content(prompt).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Batch Generation Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Efficiently process multiple requests in a batch, including automatic file handling for large jobs. This is useful for bulk operations. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let prompts = vec!["Request 1", "Request 2", "Request 3"]; let responses = gemini.generate_content_batch(prompts).await?; for response in responses { println!("{}", response); } Ok(()) } ``` -------------------------------- ### Basic File Search (RAG) Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Perform semantic document search by uploading documents and querying them with natural language. Documents are automatically chunked, embedded, and indexed. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); // Upload a document first let file_path = "./my_document.txt"; let file_handle = gemini.upload_file(file_path).await?; let query = "What is in the document?"; let response = gemini.generate_content_with_file( query, &file_handle.file_id ).await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Create Cache with System Instructions Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/caching.md Demonstrates how to create a cache with a display name and system instructions, setting a TTL for its expiration. This is useful for pre-defining agent behavior. ```rust let cached = client .create_cache() .with_display_name("Customer Service Agent".to_string()) .with_system_instruction( "You are a helpful customer service agent. Be professional, empathetic, and solution-focused." ) .with_ttl(Duration::from_secs(3600)) .execute() .await?; // Use in requests let response = client .generate_content() .with_cached_content(&cached) .with_user_message("I have an issue with my order") .execute() .await?; ``` -------------------------------- ### Comprehensive Thought Signature Usage Example Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md A detailed example covering comprehensive usage of thought signatures for structured reasoning. ```rust use gemini_rust::GeminiClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = GeminiClient::new(); let prompt = "Analyze the pros and cons of renewable energy sources, detailing each step of your reasoning."; // This example assumes the library supports detailed thought signature output. let response = client.generate_content_with_detailed_thinking(prompt).await?; println!("Comprehensive thought signature usage:\n{}", response.text()); Ok(()) } ``` -------------------------------- ### Document Retrieval Setup with Embeddings Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/embed-builder.md Embeds a list of documents for retrieval and a query, then calculates similarity scores. Ensure you have initialized the client and imported necessary types like TaskType and cosine_similarity. ```rust let docs = vec!["Product manual", "API documentation", "FAQ"]; let doc_embeddings = client .embed_content() .with_chunks(docs) .with_task_type(TaskType::RetrievalDocument) .execute_batch() .await?; let query_embedding = client .embed_content() .with_text("How to use this product?") .with_task_type(TaskType::RetrievalQuery) .execute() .await?; for doc_embedding in &doc_embeddings.embeddings { let similarity = cosine_similarity( &query_embedding.embedding.values, &doc_embedding.values, ); println!("Similarity: {}", similarity); } ``` -------------------------------- ### Gemini 3 Code Execution Example Source: https://github.com/flachesis/gemini-rust/blob/main/README.md Generate and execute Python code for mathematical calculations, data analysis, and computational tasks using Gemini 3 Pro. Requires Python execution environment. ```rust use gemini_rust::gemini::Gemini; #[tokio::main] async fn main() -> Result<(), Box> { let mut gemini = Gemini::new(); let prompt = "Calculate the factorial of 5 using Python."; let response = gemini.generate_content(prompt).await?; // The response will contain the result of the code execution println!("{}", response); Ok(()) } ``` -------------------------------- ### Get Cache Resource Name Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/caching.md Retrieve the unique name of the cached content resource. ```rust let cache_name = cached_handle.name(); // Example: "cachedContents/12345678-1234-1234-1234-123456789012" ``` -------------------------------- ### Basic Content Generation in Rust Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/INDEX.md Demonstrates how to initialize the Gemini client and generate a simple text response to a user prompt. Ensure the GEMINI_API_KEY environment variable is set. ```rust use gemini_rust::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { let client = Gemini::new(std::env::var("GEMINI_API_KEY")?)?; let response = client .generate_content() .with_user_message("What is Rust?") .execute() .await?; println!("{}", response.text()); Ok(()) } ``` -------------------------------- ### Get Specific File Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/file-operations.md Retrieves details for a specific file using its unique identifier. ```APIDOC ## get_file ### Description Retrieves a specific file by its unique ID. ### Method ```rust client.get_file(file_id) ``` ### Parameters - **file_id** (string) - The unique identifier of the file (e.g., "files/abc123"). ### Returns A `File` object representing the requested file. ``` -------------------------------- ### Using the Builder Pattern for Generation Config Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/configuration.md Demonstrates how to configure generation settings using a fluent builder pattern. This allows for setting parameters like temperature, max output tokens, and stop sequences before executing the generation request. ```rust let response = client .generate_content() .with_user_message("Generate a story") .with_temperature(1.8) .with_max_output_tokens(2000) .with_stop_sequences(vec!["THE END".to_string()]) .execute() .await?; ``` -------------------------------- ### Get Batch Operation Name Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/batch-builder.md Retrieves the resource name of the batch operation. This is a string identifier for the operation. ```rust println!("Operation: {}", handle.name()); // Output: "projects/123/locations/us-central1/operations/..." ``` -------------------------------- ### Basic API Usage (Rust) Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Demonstrates the fundamental API usage for content generation. Requires setting the GEMINI_API_KEY environment variable. ```bash GEMINI_API_KEY="your-api-key" cargo run --example simple ``` -------------------------------- ### Model Enum Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/gemini-client.md Represents the available Gemini models, including their descriptions and a method to get their string identifier. ```APIDOC ## Model Enum Represents available Gemini models. ### Variants - `Gemini25Flash` (default) - Fast and efficient model - `Gemini25FlashLite` - Lightweight variant - `Gemini25FlashImage` - Optimized for image generation - `Gemini25Pro` - Advanced model with thinking capabilities - `Gemini3Flash` - Latest flash model with thinking levels - `Gemini3Pro` - Latest pro model with code execution - `Gemini3ProImage` - Latest pro model optimized for images - `TextEmbedding004` - Text embedding model - `Custom(String)` - Custom model string ### Methods #### `as_str() -> &str` Returns the model identifier as a string. **Example**: ```rust let model_str = client.model.as_str(); // Output: "models/gemini-2.5-flash" ``` ``` -------------------------------- ### with_model_message Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/content-builder.md Adds a model message to the conversation history. This is useful for providing context or examples of desired model responses. ```APIDOC ## with_model_message ### Description Adds a model message to the conversation history. This is useful for providing context or examples of desired model responses. ### Method Rust function ### Signature `with_model_message(text: impl Into) -> Self` ### Parameters #### Path Parameters - **text** (impl Into) - Required - Model message text ### Returns - **Self** - The ContentBuilder instance for chaining. ``` -------------------------------- ### Create Cache with Tools Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/caching.md Demonstrates creating a cache that includes access to specific tools, such as Google Search. This enables cached agents to perform external actions. ```rust let cached = client .create_cache() .with_system_instruction("You are a research assistant") .with_tool(Tool::google_search()) .with_ttl(Duration::from_secs(3600)) .execute() .await?; // Use cached context with tools let response = client .generate_content() .with_cached_content(&cached) .with_user_message("Search for latest AI news") .execute() .await?; ``` -------------------------------- ### Use Custom API Endpoints (Rust) Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Demonstrates how to configure and use custom API endpoints and network configurations. ```rust custom_base_url.rs ``` -------------------------------- ### Bulk Delete All Uploaded Files (Rust) Source: https://github.com/flachesis/gemini-rust/blob/main/examples/README.md Provides an example for efficiently deleting multiple uploaded files in a single operation. ```rust files_delete_all.rs ``` -------------------------------- ### JSON: Function Call with thoughtSignature Source: https://github.com/flachesis/gemini-rust/blob/main/THOUGHT_SIGNATURE.md Example of an API response containing a function call along with its associated thought signature. ```json { "candidates": [ { "content": { "parts": [ { "functionCall": { "name": "get_current_weather", "args": { "location": "Kaohsiung Zuoying District" } }, "thoughtSignature": "CtwFAVSoXO4WSz0Ri3HddDzPQzsB8EaYsiQobiBKOzGOaAPM..." } ], "role": "model" } } ] } ``` -------------------------------- ### Get File Name - Rust Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/file-operations.md Retrieves the resource name of the uploaded file. Use this to reference the file in other API calls. ```rust let file_name = file_handle.name(); // Example output: "files/abc123def456" ``` -------------------------------- ### with_system_instruction Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/content-builder.md Sets the system instruction for the request, guiding the AI's behavior. This method is chainable for building complex requests. ```APIDOC ## with_system_instruction(text: impl Into) -> Self ### Description Sets the system instruction for the request. ### Method (Not applicable - SDK method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **text** (`impl Into`) - Required - System instruction text ### Returns - `Self` (for chaining) ### Example ```rust let response = client .generate_content() .with_system_instruction("You are an expert Python programmer") .with_user_message("Write a function to reverse a string") .execute() .await?; ``` ``` -------------------------------- ### Get a Specific File by ID Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/file-operations.md Retrieves a specific file using its unique identifier. The file ID is typically in the format 'files/your_file_id'. ```rust let file = client.get_file("files/abc123").await?; println!("Retrieved: {}", file.name()); ``` -------------------------------- ### Basic Batch Processing with Gemini Rust Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/batch-builder.md Demonstrates how to create multiple generation requests, submit them as a batch, and monitor their progress until completion. It handles both successful results and errors, printing output for each item. ```rust use gemini_rust::prelude::*; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let client = Gemini::new(std::env::var("GEMINI_API_KEY")?)?; // Create requests let requests = vec![ client.generate_content() .with_user_message("Count to 10") .build(), client.generate_content() .with_user_message("List 5 colors") .build(), client.generate_content() .with_user_message("Explain photosynthesis") .build(), ]; // Submit batch let batch_handle = client .batch_generate_content() .with_name("Example Batch".to_string()) .with_requests(requests) .execute() .await?; println!("Batch submitted: {}", batch_handle.name()); // Monitor completion loop { match batch_handle.status().await? { BatchStatus::Succeeded { results } => { for (i, item) in results.iter().enumerate() { match &item.response { Ok(response) => println!("Result {}: {}", i, response.text()), Err(e) => println!("Result {} error: {}", i, e.message), } } break; } BatchStatus::Running { completed_count, total_count, .. } => { println!("Progress: {}/{}", completed_count, total_count); tokio::time::sleep(Duration::from_secs(10)).await; } _ => break, } } Ok(()) } ``` -------------------------------- ### Handling FilesError during File Upload Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/errors.md Demonstrates how to handle `FilesError` when uploading a file. This example shows matching on `Incomplete` and `Client` error variants. ```rust match client.upload_file(bytes).upload().await { Ok(handle) => println!("Uploaded: {}", handle.name()), Err(FilesError::Incomplete { fields }) => { eprintln!("File metadata missing: {:?}", fields); } Err(FilesError::Client { source }) => { eprintln!("Upload failed: {}", source); } } ``` -------------------------------- ### List and Manage Caches Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/caching.md Demonstrates how to list all available caches and iterate through them to display their names, display names, expiration times, and TTLs. ```rust // List all caches let caches = client.list_cached_contents().await?; for cache in caches { println!("Name: {}", cache.name); println!("Display: {:?}", cache.display_name); println!("Expires: {:?}", cache.expire_time); if let Some(ttl) = cache.ttl { println!("TTL: {:?}", ttl); } } ``` -------------------------------- ### Using the Google Search Tool Source: https://github.com/flachesis/gemini-rust/blob/main/_autodocs/api-reference/tools-functions.md Enable the model to search the web by creating a Google Search tool. This is useful for retrieving up-to-date information. ```rust let tool = Tool::google_search(); let response = client .generate_content() .with_user_message("What are the latest AI developments in 2024?") .with_tool(tool) .execute() .await?; ```