Class GoogleAiGeminiBatchImageModel
- All Implemented Interfaces:
BatchImageModel
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
BatchImageModel.submit(BatchRequest)orsubmit(BatchRequest) - Poll for completion using
retrieve(String) - Process the generated images from the successful
BatchResponse - 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();
// Submit batch of image generation prompts
List<String> prompts = List.of(
"A serene mountain landscape at sunset",
"A futuristic cityscape at night"
);
BatchResponse<Response<Image>> response = model.submit(new BatchRequest<>(prompts));
// Poll for completion
String batchId = response.batchId();
BatchResponse<Response<Image>> result;
do {
Thread.sleep(5000);
result = model.retrieve(batchId);
} while (!result.state().isTerminal());
// Process results
if (result.state() == BatchState.SUCCEEDED) {
for (Response<Image> imageResponse : result.responses()) {
Image image = imageResponse.content();
// Save or process the generated image
}
}
Implements BatchImageModel for unified batch processing of image generation requests.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for constructingGoogleAiGeminiBatchImageModelinstances. -
Method Summary
Modifier and TypeMethodDescriptionbuilder()Returns a new builder for constructing GoogleAiGeminiBatchImageModel instances.voidCancels an image generation batch operation that is currently pending or running.voiddeleteBatchJob(String batchId) Deletes a batch job from the system.list(@Nullable BatchPagination batchPagination) Lists image generation batch jobs with optional pagination.BatchResponse<Response<@NonNull Image>> Retrieves the current state and results of an image generation batch operation.submit(BatchRequest<String> request) Creates a batch of image generation prompts and submits them for asynchronous processing.BatchResponse<Response<@NonNull Image>> submit(GeminiBatchRequest<String> request) Creates and enqueues a batch of image generation requests, with Gemini-specific options such as display name and priority.BatchResponse<Response<@NonNull Image>> submit(String displayName, GeminiFiles.GeminiFile file) Creates a batch of image generation requests from an uploaded file.voidwriteBatchToFile(JsonLinesWriter writer, Iterable<BatchRequestResponse.BatchFileRequest<String>> requests) Writes a batch of image generation prompts to a JSONL file for later upload and processing.
-
Method Details
-
submit
Creates a batch of image generation prompts and submits them for asynchronous processing.The returned
BatchResponserepresents the status of the batch operation.Creates and enqueues a batch of image generation requests using default display name and priority. To set a custom display name or priority, pass a
GeminiBatchRequest(it will resolve tosubmit(GeminiBatchRequest)).- Specified by:
submitin interfaceBatchImageModel- Parameters:
request- the list of text prompts describing images to generate- Returns:
- a
BatchResponserepresenting the initial state of the batch operation
-
submit
Creates and enqueues a batch of image generation requests, with Gemini-specific options such as display name and priority.- Parameters:
request- aGeminiBatchRequestcarrying the prompts and optional metadata- Returns:
- a
BatchResponserepresenting the initial state of the batch operation
-
submit
public BatchResponse<Response<@NonNull Image>> submit(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
-
writeBatchToFile
public void writeBatchToFile(JsonLinesWriter writer, Iterable<BatchRequestResponse.BatchFileRequest<String>> requests) throws IOException Writes a batch of image generation prompts to a JSONL file for later upload and processing.This method serializes image generation prompts 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 viasubmit(BatchRequest).Example usage:
Path batchFile = Files.createTempFile("image-batch", ".jsonl"); try (JsonLinesWriter writer = JsonLinesWriters.streaming(batchFile)) { List<BatchFileRequest<String>> requests = List.of( new BatchFileRequest<>("img-1", "A sunset over mountains"), new BatchFileRequest<>("img-2", "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 prompt strings, each with a unique key identifier- Throws:
IOException- if an I/O error occurs while writing to the writer- See Also:
-
retrieve
Retrieves the current state and results of an image generation batch operation.The response indicates whether the batch is still processing, completed successfully, or failed. Once completed, the response will contain the generated image data.
Polls the Gemini API to get the latest state of a previously created batch. Clients should poll this method at intervals to check the operation status until completion.
- Specified by:
retrievein interfaceBatchImageModel- Parameters:
batchId- the batch id/name obtained fromBatchImageModel.submit(BatchRequest)orsubmit(BatchRequest)- Returns:
- a
BatchResponserepresenting the current state of the batch operation
-
cancel
Cancels an image generation batch operation that is currently pending or running.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.
- Specified by:
cancelin interfaceBatchImageModel- Parameters:
batchId- the batch id/name 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
cancel(String)to cancel a running batch before deletion.- Parameters:
batchId- the batch id/name to delete- Throws:
RuntimeException- if the batch job cannot be deleted or does not exist
-
list
Lists image generation batch jobs with optional pagination.- Specified by:
listin interfaceBatchImageModel- Parameters:
batchPagination- the maximum number of batch jobs to return and token for retrieving a specific page; if null, uses server default- Returns:
- a
BatchPagecontaining image generation batch responses and pagination information
-
builder
Returns a new builder for constructing GoogleAiGeminiBatchImageModel instances.- Returns:
- a new builder instance
-