Class GoogleAiGeminiBatchImageModel
This is an asynchronous service designed for processing large volumes of image generation requests at a reduced cost (50% of standard pricing). It is ideal for non-urgent, large-scale tasks with a Service Level Objective (SLO) of 24-hour turnaround, though completion is often much quicker.
Key Features
- Cost Savings: 50% reduction compared to real-time image generation
- High Throughput: Process many image generation requests in a single batch
- Flexible Input: Submit requests inline (up to 20MB) or via uploaded files (up to 2GB) using the
GeminiFilesapi - Configurable: Supports aspect ratio, image size, and safety settings
Workflow
- Create a batch using
createBatchInline(String, Long, List)orcreateBatchFromFile(String, GeminiFiles.GeminiFile) - Poll for completion using
retrieveBatchResults(BatchRequestResponse.BatchName) - Process the generated images from the
BatchRequestResponse.BatchSuccessresponse - Optionally cancel or delete the batch job
Example Usage
GoogleAiGeminiBatchImageModel model = GoogleAiGeminiBatchImageModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash-image")
.aspectRatio("16:9")
.build();
// Create batch with image generation requests
List<ImageGenerationRequest> requests = List.of(
new ImageGenerationRequest("A serene mountain landscape at sunset"),
new ImageGenerationRequest("A futuristic cityscape at night")
);
BatchResponse<Response<Image>> response = model.createBatchInline("My Batch", 1L, requests);
// Poll for completion
BatchName batchName = ((BatchIncomplete<?>) response).batchName();
BatchResponse<Response<Image>> result;
do {
Thread.sleep(5000);
result = model.retrieveBatchResults(batchName);
} while (result instanceof BatchIncomplete);
// Process results
if (result instanceof BatchSuccess<Response<Image>> success) {
for (Response<Image> imageResponse : success.responses()) {
Image image = imageResponse.content();
// Save or process the generated image
}
}
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for constructingGoogleAiGeminiBatchImageModelinstances.static final recordRepresents a request for image generation in batch processing. -
Method Summary
Modifier and TypeMethodDescriptionbuilder()Returns a new builder for constructing GoogleAiGeminiBatchImageModel instances.voidCancels a batch operation that is currently pending or running.BatchRequestResponse.BatchResponse<Response<@NonNull Image>> createBatchFromFile(String displayName, GeminiFiles.GeminiFile file) Creates a batch of image generation requests from an uploaded file.BatchRequestResponse.BatchResponse<Response<@NonNull Image>> createBatchInline(String displayName, @Nullable Long priority, List<GoogleAiGeminiBatchImageModel.ImageGenerationRequest> requests) Creates and enqueues a batch of image generation requests for asynchronous processing.voidDeletes a batch job from the system.BatchRequestResponse.BatchList<Response<@NonNull Image>> listBatchJobs(@Nullable Integer pageSize, @Nullable String pageToken) Lists batch jobs with optional pagination.BatchRequestResponse.BatchResponse<Response<@NonNull Image>> Retrieves the current state and results of a batch operation.voidwriteBatchToFile(JsonLinesWriter writer, Iterable<BatchRequestResponse.BatchFileRequest<GoogleAiGeminiBatchImageModel.ImageGenerationRequest>> requests) Writes a batch of image generation requests to a JSONL file for later upload and processing.
-
Method Details
-
createBatchInline
public BatchRequestResponse.BatchResponse<Response<@NonNull Image>> createBatchInline(String displayName, @Nullable Long priority, List<GoogleAiGeminiBatchImageModel.ImageGenerationRequest> requests) Creates and enqueues a batch of image generation requests for asynchronous processing.This method submits multiple image generation requests as a single batch operation. The batch will be processed asynchronously, and the initial response will typically be in a
BatchRequestResponse.BatchIncompletestate.Batch processing offers a 50% cost reduction compared to real-time requests and has a 24-hour turnaround SLO, making it ideal for large-scale, non-urgent tasks.
Note: The inline API allows for a total request size of 20MB or under. For larger batches, use
createBatchFromFile(String, GeminiFiles.GeminiFile).- Parameters:
displayName- a user-defined name for the batch, used for identificationpriority- optional priority for the batch; batches with higher priority values are processed before those with lower values; negative values are allowed; defaults to 0 if nullrequests- a list of image generation requests to be processed in the batch- Returns:
- a
BatchRequestResponse.BatchResponserepresenting the initial state of the batch operation, typicallyBatchRequestResponse.BatchIncomplete
-
createBatchFromFile
public BatchRequestResponse.BatchResponse<Response<@NonNull Image>> createBatchFromFile(String displayName, GeminiFiles.GeminiFile file) Creates a batch of image generation requests from an uploaded file.This method allows you to create a batch job using a JSONL file that has been previously uploaded to the Gemini Files API. This is useful for larger batches that exceed the 20MB inline request limit, supporting up to 2GB per file.
The file must contain batch requests in JSONL format, where each line is a JSON object with a "key" and "request" field. Use
writeBatchToFile(JsonLinesWriter, Iterable)to create properly formatted JSONL files.- Parameters:
displayName- a user-defined name for the batch, used for identificationfile- the GeminiFile object representing the uploaded file containing batch requests- Returns:
- a
BatchRequestResponse.BatchResponserepresenting the initial state of the batch operation, typicallyBatchRequestResponse.BatchIncomplete - See Also:
-
writeBatchToFile
public void writeBatchToFile(JsonLinesWriter writer, Iterable<BatchRequestResponse.BatchFileRequest<GoogleAiGeminiBatchImageModel.ImageGenerationRequest>> requests) throws IOException Writes a batch of image generation requests to a JSONL file for later upload and processing.This method serializes image generation requests into JSONL (JSON Lines) format, where each line contains a single request wrapped in a
BatchRequestResponse.BatchFileRequestwith a unique key. The resulting file can be uploaded using the Gemini Files API and then used to create a batch job viacreateBatchFromFile(String, GeminiFiles.GeminiFile).Example usage:
Path batchFile = Files.createTempFile("image-batch", ".jsonl"); try (JsonLinesWriter writer = JsonLinesWriters.streaming(batchFile)) { List<BatchFileRequest<ImageGenerationRequest>> requests = List.of( new BatchFileRequest<>("img-1", new ImageGenerationRequest("A sunset over mountains")), new BatchFileRequest<>("img-2", new ImageGenerationRequest("A cat wearing a hat")) ); batchModel.writeBatchToFile(writer, requests); }- Parameters:
writer- the JsonLinesWriter to which the batch requests will be writtenrequests- an iterable collection of BatchFileRequest objects containing ImageGenerationRequest instances, each with a unique key identifier- Throws:
IOException- if an I/O error occurs while writing to the writer- See Also:
-
retrieveBatchResults
public BatchRequestResponse.BatchResponse<Response<@NonNull Image>> retrieveBatchResults(BatchRequestResponse.BatchName name) Retrieves the current state and results of a batch operation.This method polls the Gemini API to get the latest state of a previously created batch. The response can be:
BatchRequestResponse.BatchIncomplete- if the batch is still pending or runningBatchRequestResponse.BatchSuccess- if the batch completed successfully, containing all generated imagesBatchRequestResponse.BatchError- if the batch failed, containing error details
Clients should poll this method at intervals to check the operation status until completion.
- Parameters:
name- the name of the batch operation to retrieve, obtained from the initialcreateBatchInline(String, Long, List)orcreateBatchFromFile(String, GeminiFiles.GeminiFile)call- Returns:
- a
BatchRequestResponse.BatchResponserepresenting the current state of the batch operation
-
cancelBatchJob
Cancels a batch operation that is currently pending or running.This method attempts to cancel a batch job. Cancellation is only possible for batches that are in PENDING or RUNNING state. Batches that have already completed, failed, or been cancelled cannot be cancelled.
- Parameters:
name- the name of the batch operation to cancel- Throws:
HttpException- if the batch cannot be cancelled (e.g., already completed, already cancelled, or does not exist)
-
deleteBatchJob
Deletes a batch job from the system.This removes the batch job record but does not cancel it if still running. Use
cancelBatchJob(BatchRequestResponse.BatchName)to cancel a running batch before deletion.- Parameters:
name- the name of the batch job to delete- Throws:
RuntimeException- if the batch job cannot be deleted or does not exist
-
listBatchJobs
public BatchRequestResponse.BatchList<Response<@NonNull Image>> listBatchJobs(@Nullable Integer pageSize, @Nullable String pageToken) Lists batch jobs with optional pagination.Returns a paginated list of batch jobs. Use the returned page token to retrieve subsequent pages of results.
- Parameters:
pageSize- the maximum number of batch jobs to return; if null, uses server defaultpageToken- token for retrieving a specific page fromBatchRequestResponse.BatchList.pageToken(); if null, returns the first page- Returns:
- a
BatchRequestResponse.BatchListcontaining batch responses and a token for the next page
-
builder
Returns a new builder for constructing GoogleAiGeminiBatchImageModel instances.- Returns:
- a new builder instance
-