batch_delete/
batch_delete.rs

1//! Batch delete example
2//!
3//! This example demonstrates how to delete a batch operation after it has completed.
4//! Deleting a batch operation removes its metadata from the system but does not cancel
5//! a running operation.
6//!
7//! To run this example, you need to have a Gemini API key and an existing batch operation.
8//! You can get an API key from the Google AI Studio.
9//!
10//! Once you have the API key, you can run this example by setting the `GEMINI_API_KEY`
11//! and `BATCH_NAME` environment variables:
12//!
13//! ```sh
14//! export GEMINI_API_KEY=your_api_key
15//! export BATCH_NAME=your_batch_name
16//! cargo run --package gemini-rust --example batch_delete
17//! ```
18
19use gemini_rust::{BatchStatus, Gemini};
20use std::env;
21
22#[tokio::main]
23async fn main() -> Result<(), Box<dyn std::error::Error>> {
24    // Get the API key from the environment
25    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY not set");
26
27    // Get the batch name from the environment
28    let batch_name = env::var("BATCH_NAME").expect("BATCH_NAME not set");
29
30    // Create a new Gemini client
31    let gemini = Gemini::new(api_key);
32
33    // Get the batch operation
34    let batch = gemini.get_batch(&batch_name);
35
36    // Check the batch status
37    match batch.status().await {
38        Ok(status) => {
39            println!("Batch status: {:?}", status);
40
41            // Only delete completed batches (succeeded, failed, cancelled, or expired)
42            match status {
43                BatchStatus::Succeeded { .. } | BatchStatus::Cancelled | BatchStatus::Expired => {
44                    println!("Deleting batch operation...");
45                    // We need to handle the std::result::Result<(), (Batch, Error)> return type
46                    match batch.delete().await {
47                        Ok(()) => println!("Batch deleted successfully!"),
48                        Err((_batch, e)) => {
49                            println!("Failed to delete batch: {}. You can retry with the returned batch.", e);
50                            // Here you could retry: batch.delete().await, etc.
51                        }
52                    }
53                }
54                _ => {
55                    println!("Batch is still running or pending. Use cancel() to stop it, or wait for completion before deleting.");
56                }
57            }
58        }
59        Err(e) => println!("Failed to get batch status: {}", e),
60    }
61
62    Ok(())
63}