pub struct Batch {
pub name: String,
/* private fields */
}
Expand description
Represents a long-running batch operation, providing methods to manage its lifecycle.
A Batch
object is a handle to a batch operation on the Gemini API. It allows you to
check the status, cancel the operation, or delete it once it’s no longer needed.
Fields§
§name: String
The unique resource name of the batch operation, e.g., operations/batch-xxxxxxxx
.
Implementations§
Source§impl Batch
impl Batch
Sourcepub fn name(&self) -> &str
pub fn name(&self) -> &str
Returns the unique resource name of the batch operation.
Examples found in repository?
18async fn main() -> Result<(), Box<dyn std::error::Error>> {
19 // Get the API key from the environment
20 let api_key = std::env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY not set");
21
22 // Create a new Gemini client
23 let gemini = Gemini::new(api_key);
24
25 // Create the first request
26 let request1 = gemini
27 .generate_content()
28 .with_message(Message::user("What is the meaning of life?"))
29 .build();
30
31 // Create the second request
32 let request2 = gemini
33 .generate_content()
34 .with_message(Message::user("What is the best programming language?"))
35 .build();
36
37 // Create the batch request
38 let batch = gemini
39 .batch_generate_content_sync()
40 .with_request(request1)
41 .with_request(request2)
42 .execute()
43 .await?;
44
45 // Print the batch information
46 println!("Batch created successfully!");
47 println!("Batch Name: {}", batch.name());
48
49 // Wait for the batch to complete
50 println!("Waiting for batch to complete...");
51 match batch.wait_for_completion(Duration::from_secs(5)).await {
52 Ok(final_status) => {
53 // Print the final status
54 match final_status {
55 BatchStatus::Succeeded { results } => {
56 println!("Batch succeeded!");
57 for item in results {
58 match item {
59 BatchResultItem::Success { key, response } => {
60 println!("--- Response for Key {} ---", key);
61 println!("{}", response.text());
62 }
63 BatchResultItem::Error { key, error } => {
64 println!("--- Error for Key {} ---", key);
65 println!("Code: {}, Message: {}", error.code, error.message);
66 if let Some(details) = &error.details {
67 println!("Details: {}", details);
68 }
69 }
70 }
71 }
72 }
73 BatchStatus::Cancelled => {
74 println!("Batch was cancelled.");
75 }
76 BatchStatus::Expired => {
77 println!("Batch expired.");
78 }
79 _ => {
80 println!(
81 "Batch finished with an unexpected status: {:?}",
82 final_status
83 );
84 }
85 }
86 }
87 Err((_batch, e)) => {
88 println!(
89 "Batch failed: {}. You can retry with the returned batch.",
90 e
91 );
92 // Here you could retry: batch.wait_for_completion(Duration::from_secs(5)).await, etc.
93 }
94 }
95
96 Ok(())
97}
More examples
15async fn main() -> Result<()> {
16 // Get the API key from the environment
17 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set");
18
19 // Create the Gemini client
20 let gemini = Gemini::new(api_key);
21
22 // Create a batch with multiple requests
23 let mut batch_generate_content = gemini
24 .batch_generate_content_sync()
25 .with_name("batch_cancel_example".to_string());
26
27 // Add several requests to make the batch take some time to process
28 for i in 1..=10 {
29 let request = gemini
30 .generate_content()
31 .with_message(Message::user(format!(
32 "Write a creative story about a robot learning to paint, part {}. Make it at least 100 words long.",
33 i
34 )))
35 .build();
36
37 batch_generate_content = batch_generate_content.with_request(request);
38 }
39
40 // Build and start the batch
41 let batch = batch_generate_content.execute().await?;
42 println!("Batch created successfully!");
43 println!("Batch Name: {}", batch.name());
44 println!("Press CTRL-C to cancel the batch operation...");
45
46 // Wrap the batch in an Arc<Mutex<Option<Batch>>> to allow safe sharing
47 let batch = Arc::new(Mutex::new(Some(batch)));
48 let batch_clone = Arc::clone(&batch);
49
50 // Spawn a task to handle CTRL-C
51 let cancel_task = tokio::spawn(async move {
52 // Wait for CTRL-C signal
53 signal::ctrl_c().await.expect("Failed to listen for CTRL-C");
54 println!("Received CTRL-C, canceling batch operation...");
55
56 // Take the batch from the Option, leaving None.
57 // The lock is released immediately after this block.
58 let mut batch_to_cancel = batch_clone.lock().await;
59
60 if let Some(batch) = batch_to_cancel.take() {
61 // Cancel the batch operation
62 match batch.cancel().await {
63 Ok(()) => {
64 println!("Batch canceled successfully!");
65 }
66 Err((batch, e)) => {
67 println!("Failed to cancel batch: {}. Retrying...", e);
68 // Retry once
69 match batch.cancel().await {
70 Ok(()) => {
71 println!("Batch canceled successfully on retry!");
72 }
73 Err((_, retry_error)) => {
74 eprintln!("Failed to cancel batch even on retry: {}", retry_error);
75 }
76 }
77 }
78 }
79 } else {
80 println!("Batch was already processed.");
81 }
82 });
83
84 // Wait for a short moment to ensure the cancel task is ready
85 tokio::time::sleep(Duration::from_millis(100)).await;
86
87 // Wait for the batch to complete or be canceled
88 if let Some(batch) = batch.lock().await.take() {
89 println!("Waiting for batch to complete or be canceled...");
90 match batch.wait_for_completion(Duration::from_secs(5)).await {
91 Ok(final_status) => {
92 // Cancel task is no longer needed since batch completed
93 cancel_task.abort();
94
95 println!("Batch completed with status: {:?}", final_status);
96
97 // Print some details about the results
98 match final_status {
99 gemini_rust::BatchStatus::Succeeded { .. } => {
100 println!("Batch succeeded!");
101 }
102 gemini_rust::BatchStatus::Cancelled => {
103 println!("Batch was cancelled as requested.");
104 }
105 gemini_rust::BatchStatus::Expired => {
106 println!("Batch expired.");
107 }
108 _ => {
109 println!("Batch finished with an unexpected status.");
110 }
111 }
112 }
113 Err((batch, e)) => {
114 // This could happen if there was a network error while polling
115 println!("Error while waiting for batch completion: {}", e);
116
117 // Try one more time to get the status
118 match batch.status().await {
119 Ok(status) => println!("Current batch status: {:?}", status),
120 Err(status_error) => println!("Error getting final status: {}", status_error),
121 }
122 }
123 }
124 }
125
126 Ok(())
127}
Sourcepub async fn status(&self) -> Result<BatchStatus>
pub async fn status(&self) -> Result<BatchStatus>
Retrieves the current status of the batch operation by making an API call.
This method provides a snapshot of the batch’s state at a single point in time.
Examples found in repository?
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}
More examples
15async fn main() -> Result<()> {
16 // Get the API key from the environment
17 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set");
18
19 // Create the Gemini client
20 let gemini = Gemini::new(api_key);
21
22 // Create a batch with multiple requests
23 let mut batch_generate_content = gemini
24 .batch_generate_content_sync()
25 .with_name("batch_cancel_example".to_string());
26
27 // Add several requests to make the batch take some time to process
28 for i in 1..=10 {
29 let request = gemini
30 .generate_content()
31 .with_message(Message::user(format!(
32 "Write a creative story about a robot learning to paint, part {}. Make it at least 100 words long.",
33 i
34 )))
35 .build();
36
37 batch_generate_content = batch_generate_content.with_request(request);
38 }
39
40 // Build and start the batch
41 let batch = batch_generate_content.execute().await?;
42 println!("Batch created successfully!");
43 println!("Batch Name: {}", batch.name());
44 println!("Press CTRL-C to cancel the batch operation...");
45
46 // Wrap the batch in an Arc<Mutex<Option<Batch>>> to allow safe sharing
47 let batch = Arc::new(Mutex::new(Some(batch)));
48 let batch_clone = Arc::clone(&batch);
49
50 // Spawn a task to handle CTRL-C
51 let cancel_task = tokio::spawn(async move {
52 // Wait for CTRL-C signal
53 signal::ctrl_c().await.expect("Failed to listen for CTRL-C");
54 println!("Received CTRL-C, canceling batch operation...");
55
56 // Take the batch from the Option, leaving None.
57 // The lock is released immediately after this block.
58 let mut batch_to_cancel = batch_clone.lock().await;
59
60 if let Some(batch) = batch_to_cancel.take() {
61 // Cancel the batch operation
62 match batch.cancel().await {
63 Ok(()) => {
64 println!("Batch canceled successfully!");
65 }
66 Err((batch, e)) => {
67 println!("Failed to cancel batch: {}. Retrying...", e);
68 // Retry once
69 match batch.cancel().await {
70 Ok(()) => {
71 println!("Batch canceled successfully on retry!");
72 }
73 Err((_, retry_error)) => {
74 eprintln!("Failed to cancel batch even on retry: {}", retry_error);
75 }
76 }
77 }
78 }
79 } else {
80 println!("Batch was already processed.");
81 }
82 });
83
84 // Wait for a short moment to ensure the cancel task is ready
85 tokio::time::sleep(Duration::from_millis(100)).await;
86
87 // Wait for the batch to complete or be canceled
88 if let Some(batch) = batch.lock().await.take() {
89 println!("Waiting for batch to complete or be canceled...");
90 match batch.wait_for_completion(Duration::from_secs(5)).await {
91 Ok(final_status) => {
92 // Cancel task is no longer needed since batch completed
93 cancel_task.abort();
94
95 println!("Batch completed with status: {:?}", final_status);
96
97 // Print some details about the results
98 match final_status {
99 gemini_rust::BatchStatus::Succeeded { .. } => {
100 println!("Batch succeeded!");
101 }
102 gemini_rust::BatchStatus::Cancelled => {
103 println!("Batch was cancelled as requested.");
104 }
105 gemini_rust::BatchStatus::Expired => {
106 println!("Batch expired.");
107 }
108 _ => {
109 println!("Batch finished with an unexpected status.");
110 }
111 }
112 }
113 Err((batch, e)) => {
114 // This could happen if there was a network error while polling
115 println!("Error while waiting for batch completion: {}", e);
116
117 // Try one more time to get the status
118 match batch.status().await {
119 Ok(status) => println!("Current batch status: {:?}", status),
120 Err(status_error) => println!("Error getting final status: {}", status_error),
121 }
122 }
123 }
124 }
125
126 Ok(())
127}
Sourcepub async fn cancel(self) -> Result<(), (Self, Error)>
pub async fn cancel(self) -> Result<(), (Self, Error)>
Sends a request to the API to cancel the batch operation.
Cancellation is not guaranteed to be instantaneous. The operation may continue to run for some time after the cancellation request is made.
Consumes the batch. If cancellation fails, returns the batch and error information so it can be retried.
Examples found in repository?
15async fn main() -> Result<()> {
16 // Get the API key from the environment
17 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set");
18
19 // Create the Gemini client
20 let gemini = Gemini::new(api_key);
21
22 // Create a batch with multiple requests
23 let mut batch_generate_content = gemini
24 .batch_generate_content_sync()
25 .with_name("batch_cancel_example".to_string());
26
27 // Add several requests to make the batch take some time to process
28 for i in 1..=10 {
29 let request = gemini
30 .generate_content()
31 .with_message(Message::user(format!(
32 "Write a creative story about a robot learning to paint, part {}. Make it at least 100 words long.",
33 i
34 )))
35 .build();
36
37 batch_generate_content = batch_generate_content.with_request(request);
38 }
39
40 // Build and start the batch
41 let batch = batch_generate_content.execute().await?;
42 println!("Batch created successfully!");
43 println!("Batch Name: {}", batch.name());
44 println!("Press CTRL-C to cancel the batch operation...");
45
46 // Wrap the batch in an Arc<Mutex<Option<Batch>>> to allow safe sharing
47 let batch = Arc::new(Mutex::new(Some(batch)));
48 let batch_clone = Arc::clone(&batch);
49
50 // Spawn a task to handle CTRL-C
51 let cancel_task = tokio::spawn(async move {
52 // Wait for CTRL-C signal
53 signal::ctrl_c().await.expect("Failed to listen for CTRL-C");
54 println!("Received CTRL-C, canceling batch operation...");
55
56 // Take the batch from the Option, leaving None.
57 // The lock is released immediately after this block.
58 let mut batch_to_cancel = batch_clone.lock().await;
59
60 if let Some(batch) = batch_to_cancel.take() {
61 // Cancel the batch operation
62 match batch.cancel().await {
63 Ok(()) => {
64 println!("Batch canceled successfully!");
65 }
66 Err((batch, e)) => {
67 println!("Failed to cancel batch: {}. Retrying...", e);
68 // Retry once
69 match batch.cancel().await {
70 Ok(()) => {
71 println!("Batch canceled successfully on retry!");
72 }
73 Err((_, retry_error)) => {
74 eprintln!("Failed to cancel batch even on retry: {}", retry_error);
75 }
76 }
77 }
78 }
79 } else {
80 println!("Batch was already processed.");
81 }
82 });
83
84 // Wait for a short moment to ensure the cancel task is ready
85 tokio::time::sleep(Duration::from_millis(100)).await;
86
87 // Wait for the batch to complete or be canceled
88 if let Some(batch) = batch.lock().await.take() {
89 println!("Waiting for batch to complete or be canceled...");
90 match batch.wait_for_completion(Duration::from_secs(5)).await {
91 Ok(final_status) => {
92 // Cancel task is no longer needed since batch completed
93 cancel_task.abort();
94
95 println!("Batch completed with status: {:?}", final_status);
96
97 // Print some details about the results
98 match final_status {
99 gemini_rust::BatchStatus::Succeeded { .. } => {
100 println!("Batch succeeded!");
101 }
102 gemini_rust::BatchStatus::Cancelled => {
103 println!("Batch was cancelled as requested.");
104 }
105 gemini_rust::BatchStatus::Expired => {
106 println!("Batch expired.");
107 }
108 _ => {
109 println!("Batch finished with an unexpected status.");
110 }
111 }
112 }
113 Err((batch, e)) => {
114 // This could happen if there was a network error while polling
115 println!("Error while waiting for batch completion: {}", e);
116
117 // Try one more time to get the status
118 match batch.status().await {
119 Ok(status) => println!("Current batch status: {:?}", status),
120 Err(status_error) => println!("Error getting final status: {}", status_error),
121 }
122 }
123 }
124 }
125
126 Ok(())
127}
Sourcepub async fn delete(self) -> Result<(), (Self, Error)>
pub async fn delete(self) -> Result<(), (Self, Error)>
Deletes the batch operation resource from the server.
Note: This method indicates that the client is no longer interested in the operation result.
It does not cancel a running operation. To stop a running batch, use the cancel
method.
This method should typically be used after the batch has completed.
Consumes the batch. If deletion fails, returns the batch and error information so it can be retried.
Examples found in repository?
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}
Sourcepub async fn wait_for_completion(
self,
delay: Duration,
) -> Result<BatchStatus, (Self, Error)>
pub async fn wait_for_completion( self, delay: Duration, ) -> Result<BatchStatus, (Self, Error)>
Waits for the batch operation to complete by periodically polling its status.
This method polls the batch status with a specified delay until the operation reaches a terminal state (Succeeded, Failed, Cancelled, or Expired).
Consumes the batch and returns the final status. If there’s an error during polling, the batch is returned in the error variant so it can be retried.
Examples found in repository?
18async fn main() -> Result<(), Box<dyn std::error::Error>> {
19 // Get the API key from the environment
20 let api_key = std::env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY not set");
21
22 // Create a new Gemini client
23 let gemini = Gemini::new(api_key);
24
25 // Create the first request
26 let request1 = gemini
27 .generate_content()
28 .with_message(Message::user("What is the meaning of life?"))
29 .build();
30
31 // Create the second request
32 let request2 = gemini
33 .generate_content()
34 .with_message(Message::user("What is the best programming language?"))
35 .build();
36
37 // Create the batch request
38 let batch = gemini
39 .batch_generate_content_sync()
40 .with_request(request1)
41 .with_request(request2)
42 .execute()
43 .await?;
44
45 // Print the batch information
46 println!("Batch created successfully!");
47 println!("Batch Name: {}", batch.name());
48
49 // Wait for the batch to complete
50 println!("Waiting for batch to complete...");
51 match batch.wait_for_completion(Duration::from_secs(5)).await {
52 Ok(final_status) => {
53 // Print the final status
54 match final_status {
55 BatchStatus::Succeeded { results } => {
56 println!("Batch succeeded!");
57 for item in results {
58 match item {
59 BatchResultItem::Success { key, response } => {
60 println!("--- Response for Key {} ---", key);
61 println!("{}", response.text());
62 }
63 BatchResultItem::Error { key, error } => {
64 println!("--- Error for Key {} ---", key);
65 println!("Code: {}, Message: {}", error.code, error.message);
66 if let Some(details) = &error.details {
67 println!("Details: {}", details);
68 }
69 }
70 }
71 }
72 }
73 BatchStatus::Cancelled => {
74 println!("Batch was cancelled.");
75 }
76 BatchStatus::Expired => {
77 println!("Batch expired.");
78 }
79 _ => {
80 println!(
81 "Batch finished with an unexpected status: {:?}",
82 final_status
83 );
84 }
85 }
86 }
87 Err((_batch, e)) => {
88 println!(
89 "Batch failed: {}. You can retry with the returned batch.",
90 e
91 );
92 // Here you could retry: batch.wait_for_completion(Duration::from_secs(5)).await, etc.
93 }
94 }
95
96 Ok(())
97}
More examples
15async fn main() -> Result<()> {
16 // Get the API key from the environment
17 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set");
18
19 // Create the Gemini client
20 let gemini = Gemini::new(api_key);
21
22 // Create a batch with multiple requests
23 let mut batch_generate_content = gemini
24 .batch_generate_content_sync()
25 .with_name("batch_cancel_example".to_string());
26
27 // Add several requests to make the batch take some time to process
28 for i in 1..=10 {
29 let request = gemini
30 .generate_content()
31 .with_message(Message::user(format!(
32 "Write a creative story about a robot learning to paint, part {}. Make it at least 100 words long.",
33 i
34 )))
35 .build();
36
37 batch_generate_content = batch_generate_content.with_request(request);
38 }
39
40 // Build and start the batch
41 let batch = batch_generate_content.execute().await?;
42 println!("Batch created successfully!");
43 println!("Batch Name: {}", batch.name());
44 println!("Press CTRL-C to cancel the batch operation...");
45
46 // Wrap the batch in an Arc<Mutex<Option<Batch>>> to allow safe sharing
47 let batch = Arc::new(Mutex::new(Some(batch)));
48 let batch_clone = Arc::clone(&batch);
49
50 // Spawn a task to handle CTRL-C
51 let cancel_task = tokio::spawn(async move {
52 // Wait for CTRL-C signal
53 signal::ctrl_c().await.expect("Failed to listen for CTRL-C");
54 println!("Received CTRL-C, canceling batch operation...");
55
56 // Take the batch from the Option, leaving None.
57 // The lock is released immediately after this block.
58 let mut batch_to_cancel = batch_clone.lock().await;
59
60 if let Some(batch) = batch_to_cancel.take() {
61 // Cancel the batch operation
62 match batch.cancel().await {
63 Ok(()) => {
64 println!("Batch canceled successfully!");
65 }
66 Err((batch, e)) => {
67 println!("Failed to cancel batch: {}. Retrying...", e);
68 // Retry once
69 match batch.cancel().await {
70 Ok(()) => {
71 println!("Batch canceled successfully on retry!");
72 }
73 Err((_, retry_error)) => {
74 eprintln!("Failed to cancel batch even on retry: {}", retry_error);
75 }
76 }
77 }
78 }
79 } else {
80 println!("Batch was already processed.");
81 }
82 });
83
84 // Wait for a short moment to ensure the cancel task is ready
85 tokio::time::sleep(Duration::from_millis(100)).await;
86
87 // Wait for the batch to complete or be canceled
88 if let Some(batch) = batch.lock().await.take() {
89 println!("Waiting for batch to complete or be canceled...");
90 match batch.wait_for_completion(Duration::from_secs(5)).await {
91 Ok(final_status) => {
92 // Cancel task is no longer needed since batch completed
93 cancel_task.abort();
94
95 println!("Batch completed with status: {:?}", final_status);
96
97 // Print some details about the results
98 match final_status {
99 gemini_rust::BatchStatus::Succeeded { .. } => {
100 println!("Batch succeeded!");
101 }
102 gemini_rust::BatchStatus::Cancelled => {
103 println!("Batch was cancelled as requested.");
104 }
105 gemini_rust::BatchStatus::Expired => {
106 println!("Batch expired.");
107 }
108 _ => {
109 println!("Batch finished with an unexpected status.");
110 }
111 }
112 }
113 Err((batch, e)) => {
114 // This could happen if there was a network error while polling
115 println!("Error while waiting for batch completion: {}", e);
116
117 // Try one more time to get the status
118 match batch.status().await {
119 Ok(status) => println!("Current batch status: {:?}", status),
120 Err(status_error) => println!("Error getting final status: {}", status_error),
121 }
122 }
123 }
124 }
125
126 Ok(())
127}