All guides

Gemini Batch API: submit a JSONL file and reconcile each result

Submit non-urgent generateContent requests as a JSONL batch job, poll its state, and check every result line. No product or API was run in this batch.

AINav editorsWritten / Updated Sources checked
On this page

At a glance

This guide covers one task: handing a set of requests that can wait to the Gemini Batch API, then checking each result individually. The source page says this feature is currently only available with the generateContent API, so Interactions are out of scope. It also says Batch API is meant for large-scale, non-urgent work such as data pre-processing or running evaluations. Below, API facts reported by the source, editorial checks and the actual execution scope are kept apart. Nothing was called or run in this batch.

Task workflow

  1. Two submission methods and their outputs

    The source offers two ways to submit. Inline requests put a list of GenerateContentRequest objects directly in the batch creation request. They suit smaller batches whose total size stays under 20MB, and the output is a list of inlineResponse objects. An input file is a JSON Lines file in which each line is a complete GenerateContentRequest. The source recommends it for larger requests, and the output is a JSONL file in which each line is either a GenerateContentResponse or a status object. Because the outputs differ in shape, the code that reads them differs too.

  2. The key ties each line to its result

    Each line of an input file must be a JSON object holding a user-defined key and a request object. The source says the key appears in the response to show which output belongs to which request. For example, the request keyed request-1 gets a response annotated with the same key. The file is uploaded through the File API, and an input file can be at most 2GB. When reconciling, match on the key rather than relying only on the order of the output.

  3. Job state and per-request result are separate layers

    A batch job has its own states: JOB_STATE_PENDING, JOB_STATE_RUNNING, JOB_STATE_SUCCEEDED, JOB_STATE_FAILED, JOB_STATE_CANCELLED and JOB_STATE_EXPIRED. JOB_STATE_SUCCEEDED means the job completed and results can be retrieved. The source's recommendations separately say to check failedRequestCount in batchStats after completion and, for file output, to parse each line and decide whether it is a GenerateContentResponse or a status object reporting an error for that request. A succeeded job therefore does not mean every request succeeded.

  4. Turnaround, pricing and duplicate submission

    The source prices Batch API at 50% of the standard interactive API cost for the equivalent model, and gives 24 hours as the target turnaround, with many jobs finishing much faster. It does not promise completion within 24 hours. JOB_STATE_EXPIRED means the job ran or waited for more than 48 hours and has no results; you can resubmit or split the requests into smaller batches. Creating a batch job is not idempotent: sending the same creation request twice creates two separate jobs. No paid API was called here, 50% is the source's statement, and this guide calculates no savings.

Inputs, processing and deliverables from official documentation; the product was not run in this batch.

Task and deliverable

This guide covers one task: handing a set of requests that can wait to the Gemini Batch API, then checking each result individually. The source page says this feature is currently only available with the generateContent API, so Interactions are out of scope. It also says Batch API is meant for large-scale, non-urgent work such as data pre-processing or running evaluations. Below, API facts reported by the source, editorial checks and the actual execution scope are kept apart. Nothing was called or run in this batch.

Prepare the input and environment

  • An account that can use the Gemini API, and an environment where you are allowed to use it. The source does not describe authentication, and the genai.Client() call in the excerpts does not show how credentials are set, so confirm that in the official documentation.
  • A Python SDK environment that supports the shown from google import genai and from google.genai import types imports. Consult official SDK documentation for the distribution name, installation steps and supported versions. No dependency was installed or run in this batch.
  • A set of known, non-urgent requests. Each must be a valid GenerateContentRequest object with a user-defined key.
  • A model that the Models page lists as supporting Batch API. The source example uses the model name gemini-4-hydrogen; whether it fits your account is for you to check. The source also says the modalities supported by Batch API match those of the interactive (non-batch) API.

Mechanism and data flow

Two submission methods and their outputs: The source offers two ways to submit. Inline requests put a list of GenerateContentRequest objects directly in the batch creation request. They suit smaller batches whose total size stays under 20MB, and the output is a list of inlineResponse objects. An input file is a JSON Lines file in which each line is a complete GenerateContentRequest. The source recommends it for larger requests, and the output is a JSONL file in which each line is either a GenerateContentResponse or a status object. Because the outputs differ in shape, the code that reads them differs too.

The key ties each line to its result: Each line of an input file must be a JSON object holding a user-defined key and a request object. The source says the key appears in the response to show which output belongs to which request. For example, the request keyed request-1 gets a response annotated with the same key. The file is uploaded through the File API, and an input file can be at most 2GB. When reconciling, match on the key rather than relying only on the order of the output.

Job state and per-request result are separate layers: A batch job has its own states: JOB_STATE_PENDING, JOB_STATE_RUNNING, JOB_STATE_SUCCEEDED, JOB_STATE_FAILED, JOB_STATE_CANCELLED and JOB_STATE_EXPIRED. JOB_STATE_SUCCEEDED means the job completed and results can be retrieved. The source's recommendations separately say to check failedRequestCount in batchStats after completion and, for file output, to parse each line and decide whether it is a GenerateContentResponse or a status object reporting an error for that request. A succeeded job therefore does not mean every request succeeded.

Turnaround, pricing and duplicate submission: The source prices Batch API at 50% of the standard interactive API cost for the equivalent model, and gives 24 hours as the target turnaround, with many jobs finishing much faster. It does not promise completion within 24 hours. JOB_STATE_EXPIRED means the job ran or waited for more than 48 hours and has no results; you can resubmit or split the requests into smaller batches. Creating a batch job is not idempotent: sending the same creation request twice creates two separate jobs. No paid API was called here, 50% is the source's statement, and this guide calculates no savings.

Workflow map

Workflow stages and responsibilities
StageWhat happens
Two submission methods and their outputsThe source offers two ways to submit.
The key ties each line to its resultEach line of an input file must be a JSON object holding a user-defined key and a request object.
Job state and per-request result are separate layersA batch job has its own states: JOB_STATE_PENDING, JOB_STATE_RUNNING, JOB_STATE_SUCCEEDED, JOB_STATE_FAILED, JOB_STATE_CANCELLED and JOB_STATE_EXPIRED.
Turnaround, pricing and duplicate submissionThe source prices Batch API at 50% of the standard interactive API cost for the equivalent model, and gives 24 hours as the target turnaround, with many jobs finishing much faster.

Complete the task

Confirm scope and prepare the requests: First confirm that the task goes through generateContent and that the results can wait. Then choose a submission method: an input file for many or large requests, inline for small batches whose total size stays under 20MB. This guide develops only the input file. Each request needs a user-defined key and a request object. The source adds that each request can carry other parameters such as system instructions or tools, as inline requests can, and that multimodal input can reference other uploaded files.

Write and upload the JSONL file: The source's sample file has two lines: request-1 asks for a description of photosynthesis, and request-2 asks for the main ingredients in a Margherita pizza. The supplied Python excerpt writes those two dictionaries line by line with json.dumps into my-batch-requests.jsonl, uploads it with client.files.upload using display_name my-batch-requests and mime_type jsonl, and prints uploaded_file.name. It requires a Python SDK environment that supports the shown imports and an already configured client. Confirm authentication for the actual environment separately. The source prose mentions the file name my-batch-requests.json, which differs from the .jsonl in the code, so use the file you actually write and upload.

Create the batch job from the uploaded file: The creation excerpt contains only client.batches.create, with model, src and a config holding display_name (file-upload-job-1 in the example), then prints file_batch_job.name. It is not a standalone program: its comment says uploaded_file comes from the previous step, so running it alone would lack that variable. The source says creating a job returns a job name, used later for monitoring and for retrieving results. Save that name. Because creation is not idempotent, do not resend the same creation request as a retry.

Poll the job state: The polling excerpt sets job_name to the placeholder YOUR_BATCH_JOB_NAME (the comment suggests a form like batches/your-batch-id), reads the job with client.batches.get, and rereads it every 30 seconds until state.name is one of four terminal states: JOB_STATE_SUCCEEDED, JOB_STATE_FAILED, JOB_STATE_CANCELLED or JOB_STATE_EXPIRED. It then prints the final state and, for JOB_STATE_FAILED, batch_job.error. The loop has no timeout or attempt limit, so you decide when to stop. The source also mentions subscribing to batch.succeeded through Webhooks instead of polling, which this guide does not cover.

Retrieve results and identify where they landed: The retrieval excerpt proceeds only when the state is JOB_STATE_SUCCEEDED. If batch_job.dest.file_name exists, it downloads that file with client.files.download and prints it decoded as utf-8. If batch_job.dest.inlined_responses exists, it checks each item for response or error. If neither exists, it prints No results found (neither file nor inline). For a job that did not succeed, it prints the final state and batch_job.error. For this guide's input-file flow, the expected location is a result file; that is an expectation drawn from the source, not something observed in this batch.

Reconcile line by line (editorial recommendation): This step and the stopping rules below are editorial recommendations, not official behavior. The official excerpt only prints the file content and does not parse it. Write your own parsing that reads the output line by line and checks that every key has a matching line, whether each line is a GenerateContentResponse or a status object, and that status-object lines are counted as per-request failures, then compare against failedRequestCount in batchStats. These are static and semantic checks of structure and correspondence. They cannot show that the answers themselves are correct.

Stopping conditions and cleanup (editorial recommendation): success requires JOB_STATE_SUCCEEDED, exactly one output per input key, no status-object lines and separate acceptance of answer content. Record job-level failure, cancellation or expiry separately from per-request status objects. If dest has neither a file nor inline responses, treat results as not retrieved. If uploading, creating, polling, downloading, parsing, cancelling or deleting fails, record the error and any known file and job names. If creation identity or remote state is uncertain, stop automatic submission and cleanup, retaining pending actions and credential configuration needed to resume; creation is not idempotent. Stopping local polling does not stop a remote job. To stop remote processing, cancel by its known name and check the state again. The source's client.batches.cancel stops new-request processing, and client.batches.delete also removes the job from the list; their excerpts need existing job objects. Neither proves that uploaded files were removed. Consult official Files API documentation before cleaning up input files; this guide adds no unsupported call. Remove temporary credentials only after remote state and remaining actions are confirmed and credentials are no longer needed. Delete temporary copies as appropriate, preserving accepted results and unfinished actions.

Worked example

The documented example runs as follows. The input file has two lines: the request keyed request-1 asks about the process of photosynthesis, and the request keyed request-2 asks about the main ingredients in a Margherita pizza. After upload you get uploaded_file.name, use it as src to create the job and obtain a job name, then poll with that name and retrieve the results. Per the source description, each result line should carry request-1 or request-2 and be either a response or a status object. This is an expectation based on the official documentation. It was not run in this batch, and no actual output was observed.

Official documentation excerpt: read under the stated prerequisites; not run in this batch
json
{"key": "request-1", "request": {"contents": [{"parts": [{"text": "Describe the process of photosynthesis."}]}]}}
{"key": "request-2", "request": {"contents": [{"parts": [{"text": "What are the main ingredients in a Margherita pizza?"}]}]}}
Official documentation excerpt: read under the stated prerequisites; not run in this batch
python

import json
from google import genai
from google.genai import types

client = genai.Client()

# Create a sample JSONL file
with open("my-batch-requests.jsonl", "w") as f:
    requests = [
        {"key": "request-1", "request": {"contents": [{"parts": [{"text": "Describe the process of photosynthesis."}]}]}},
        {"key": "request-2", "request": {"contents": [{"parts": [{"text": "What are the main ingredients in a Margherita pizza?"}]}]}}
    ]
    for req in requests:
        f.write(json.dumps(req) + "\n")

# Upload the file to the File API
uploaded_file = client.files.upload(
    file='my-batch-requests.jsonl',
    config=types.UploadFileConfig(display_name='my-batch-requests', mime_type='jsonl')
)

print(f"Uploaded file: {uploaded_file.name}")
Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
from google import genai

# Assumes `uploaded_file` is the file object from the previous step
client = genai.Client()
file_batch_job = client.batches.create(
    model="gemini-4-hydrogen",
    src=uploaded_file.name,
    config={
        'display_name': "file-upload-job-1",
    },
)

print(f"Created batch job: {file_batch_job.name}")
Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
import time
from google import genai

client = genai.Client()

# Use the name of the job you want to check
# e.g., inline_batch_job.name from the previous step
job_name = "YOUR_BATCH_JOB_NAME" # (e.g. 'batches/your-batch-id')
batch_job = client.batches.get(name=job_name)

completed_states = set([
    'JOB_STATE_SUCCEEDED',
    'JOB_STATE_FAILED',
    'JOB_STATE_CANCELLED',
    'JOB_STATE_EXPIRED',
])

print(f"Polling status for job: {job_name}")
batch_job = client.batches.get(name=job_name) # Initial get
while batch_job.state.name not in completed_states:
  print(f"Current state: {batch_job.state.name}")
  time.sleep(30) # Wait for 30 seconds before polling again
  batch_job = client.batches.get(name=job_name)

print(f"Job finished with state: {batch_job.state.name}")
if batch_job.state.name == 'JOB_STATE_FAILED':
    print(f"Error: {batch_job.error}")
Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
import json
from google import genai

client = genai.Client()

# Use the name of the job you want to check
# e.g., inline_batch_job.name from the previous step
job_name = "YOUR_BATCH_JOB_NAME"
batch_job = client.batches.get(name=job_name)

if batch_job.state.name == 'JOB_STATE_SUCCEEDED':

    # If batch job was created with a file
    if batch_job.dest and batch_job.dest.file_name:
        # Results are in a file
        result_file_name = batch_job.dest.file_name
        print(f"Results are in file: {result_file_name}")

        print("Downloading result file content...")
        file_content = client.files.download(file=result_file_name)
        # Process file_content (bytes) as needed
        print(file_content.decode('utf-8'))

    # If batch job was created with inline request
    # (for embeddings, use batch_job.dest.inlined_embed_content_responses)
    elif batch_job.dest and batch_job.dest.inlined_responses:
        # Results are inline
        print("Results are inline:")
        for i, inline_response in enumerate(batch_job.dest.inlined_responses):
            print(f"Response {i+1}:")
            if inline_response.response:
                # Accessing response, structure may vary.
                try:
                    print(inline_response.response.text)
                except AttributeError:
                    print(inline_response.response) # Fallback
            elif inline_response.error:
                print(f"Error: {inline_response.error}")
    else:
        print("No results found (neither file nor inline).")
else:
    print(f"Job did not succeed. Final state: {batch_job.state.name}")
    if batch_job.error:
        print(f"Error: {batch_job.error}")
Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
client.batches.cancel(name=batch_job_to_cancel.name)
Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
client.batches.delete(name=batch_job_to_delete.name)

Check the result and failure paths

  • Input check (editorial recommendation): every line is valid JSON with a key and a request, keys are unique, and the file does not exceed 2GB.
  • State check: read the state with the saved job name, retrieve results only after JOB_STATE_SUCCEEDED, read error on JOB_STATE_FAILED, and for JOB_STATE_EXPIRED expect no results and resubmit or split the batch.
  • Result check: every key has a matching output line, each line is classified as a response or a status object, and the count agrees with failedRequestCount.
  • Empty-output check: if dest holds neither a file nor inline responses, treat the run as incomplete rather than successful.
  • Exit check (editorial recommendation): verify remote state and pending actions. Retain errors and known file and job names after API or parsing failures; avoid automatic resubmission when identity is uncertain. If stopping remotely, cancel and recheck state after ending polling. Clean temporary credentials only when no remaining action needs them.

Scope and limits

  • The source says only that this feature is currently only available with the generateContent API. This guide does not extend that to other APIs and does not mix in Interactions.
  • 24 hours is a target turnaround, not a guarantee. The 50% price is the source's statement; current pricing was not checked and no savings figure is given.
  • The official excerpts are shown separately: the create and polling excerpts depend on uploaded_file and the job name from earlier steps, and the cancel and delete excerpts depend on an existing job object. They are not one runnable program and do not prove semantic correctness of the results.
  • Line-by-line parsing, stopping conditions and credential cleanup are editorial recommendations. The source provides no other cancellation interface, and none is invented here.

No product or API was called in this batch, no dependency was installed and no code was run. The states, outputs and example results above come from the official documentation's description or from editorial expectation, not from observed execution.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. Gemini · Official sources
    View details