Class GoogleAiGeminiBatchImageModel

java.lang.Object
dev.langchain4j.model.googleai.GoogleAiGeminiBatchImageModel
All Implemented Interfaces:
BatchImageModel

@Experimental public final class GoogleAiGeminiBatchImageModel extends Object implements BatchImageModel
Provides an interface for batch image generation using the Gemini Batch API.

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 GeminiFiles api
  • Configurable: Supports aspect ratio, image size, and safety settings

Workflow

  1. Create a batch using BatchImageModel.submit(BatchRequest) or submit(BatchRequest)
  2. Poll for completion using retrieve(String)
  3. Process the generated images from the successful BatchResponse
  4. 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:
  • Method Details

    • submit

      public BatchResponse<Response<Image>> submit(BatchRequest<String> request)
      Creates a batch of image generation prompts and submits them for asynchronous processing.

      The returned BatchResponse represents 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 to submit(GeminiBatchRequest)).

      Specified by:
      submit in interface BatchImageModel
      Parameters:
      request - the list of text prompts describing images to generate
      Returns:
      a BatchResponse representing the initial state of the batch operation
    • submit

      public 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.
      Parameters:
      request - a GeminiBatchRequest carrying the prompts and optional metadata
      Returns:
      a BatchResponse representing 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 identification
      file - 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.BatchFileRequest with a unique key. The resulting file can be uploaded using the Gemini Files API and then used to create a batch job via submit(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 written
      requests - 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

      public BatchResponse<Response<@NonNull Image>> retrieve(String batchId)
      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:
      retrieve in interface BatchImageModel
      Parameters:
      batchId - the batch id/name obtained from BatchImageModel.submit(BatchRequest) or submit(BatchRequest)
      Returns:
      a BatchResponse representing the current state of the batch operation
    • cancel

      public void cancel(String batchId)
      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:
      cancel in interface BatchImageModel
      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

      public void deleteBatchJob(String batchId)
      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

      public BatchPage<Response<@NonNull Image>> list(@Nullable BatchPagination batchPagination)
      Lists image generation batch jobs with optional pagination.
      Specified by:
      list in interface BatchImageModel
      Parameters:
      batchPagination - the maximum number of batch jobs to return and token for retrieving a specific page; if null, uses server default
      Returns:
      a BatchPage containing image generation batch responses and pagination information
    • builder

      Returns a new builder for constructing GoogleAiGeminiBatchImageModel instances.
      Returns:
      a new builder instance