AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring the Gemini Batch API for High-Volume Classification and Offline Evaluations

심동규 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Running half a million support tickets through an interactive LLM endpoint is an expensive mistake. You hit rate limits (HTTP 429), write complex retry exponential backoffs, watch your connection pools time out, and pay full sticker price for tokens you did not need returned in 400 milliseconds.

At 365Finds, we evaluate AI infrastructure through a pragmatic lens: if an end user is not waiting on the other side of a spinning spinner, you should never pay interactive rates. The Gemini Batch API cuts token costs by an immediate 50% across both input prompts and output candidates, bypasses standard interactive rate quotas, and processes workloads asynchronously within a target 24-hour turnaround window.

While Gemini Context Caching solves the problem of querying a single, massive static prefix (like a 200,000-token repository) repeatedly, batch processing solves the opposite challenge: millions of independent, heterogeneous classification prompts and offline evaluation rubrics. Here is how 365Finds configures the Gemini Batch API using the official google-genai SDK for production pipelines.


The Cost and Quota Economics: Why Batch Wins

Before writing code, understand the trade-offs. The Gemini Batch API operates on an asynchronous queue with distinct pricing and throughput characteristics:


Step 1: Formatting the JSON Lines (.jsonl) Input

Batch inference requires a JSON Lines (.jsonl) file where every line represents an independent API call. For high-volume classification and automated offline scoring (LLM-as-a-judge), you should enforce structured JSON output and attach a unique tracking identifier.

Each entry must include:

  1. key: A unique string identifier. Because batch execution can return completed items out of order, this key is your sole mechanism for reconciling model outputs back to your internal database records.
  2. request: A valid GenerateContentRequest object containing contents and optional generation_config.

Here is an example classification_requests.jsonl file configured for multi-class ticket triage with structured outputs:

{"key": "ticket_10821", "request": {"contents": [{"role": "user", "parts": [{"text": "Customer ticket: I cannot log in after resetting my password yesterday.\nAssign priority (high, medium, low) and category (billing, auth, bug)."}]}], "generation_config": {"response_mime_type": "application/json", "temperature": 0.0}}}
{"key": "ticket_10822", "request": {"contents": [{"role": "user", "parts": [{"text": "Customer ticket: Can you send me the invoice for June 2026?\nAssign priority (high, medium, low) and category (billing, auth, bug)."}]}], "generation_config": {"response_mime_type": "application/json", "temperature": 0.0}}}

365Finds Tip: Always set temperature: 0.0 for offline evaluation and categorization. You want deterministic classification rubrics, not imaginative token sampling.


Step 2: Uploading the Batch File and Creating the Job

Using the official Google GenAI Python SDK (google-genai), upload your .jsonl payload using the Files API and submit the batch job.

Install the current SDK if you haven't already:

pip install google-genai

The submission script:

import os
from google import genai
from google.genai import types

# 1. Initialize client using GEMINI_API_KEY from environment
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))

input_file_path = "classification_requests.jsonl"

# 2. Upload the JSONL dataset to Google Files API
print("Uploading input dataset to Gemini Files API...")
uploaded_file = client.files.upload(
    file=input_file_path,
    config=types.UploadFileConfig(
        display_name="support_ticket_classification_run",
        mime_type="application/jsonl"
    )
)
print(f"Uploaded File Reference: {uploaded_file.name}")

# 3. Create the Batch Job
# 365Finds preference: gemini-2.5-flash offers unbeatable cost/accuracy for classification
batch_job = client.batches.create(
    model="gemini-2.5-flash",
    src=uploaded_file.name,
    config=types.CreateBatchJobConfig(
        display_name="support_ticket_batch_2026_q4"
    )
)

print(f"Batch Job Created Successfully.")
print(f"Job Name: {batch_job.name}")
print(f"Initial State: {batch_job.state.name}")

Step 3: Lifecycle Polling and State Monitoring

Because batch jobs execute asynchronously, your orchestrator (Airflow, Celery, or a lightweight worker script) must poll the job resource until it reaches a terminal status.

The primary states are:

Here is an automated polling loop with backoff:

import time
from google import genai

client = genai.Client()
job_name = batch_job.name  # e.g., "batches/xyz123abc456"

print(f"Tracking status for {job_name}...")

terminal_failure_states = {
    "JOB_STATE_FAILED",
    "JOB_STATE_CANCELLED",
    "JOB_STATE_EXPIRED"
}

poll_interval_seconds = 30

while True:
    job_status = client.batches.get(name=job_name)
    current_state = job_status.state.name
    print(f"Current Status: {current_state}")

    if current_state == "JOB_STATE_SUCCEEDED":
        print("Batch processing completed successfully!")
        break

    if current_state in terminal_failure_states:
        raise RuntimeError(f"Batch processing terminated with failure state: {current_state}")

    time.sleep(poll_interval_seconds)

Step 4: Downloading and Parsing Results Safely

When job_status.state.name == "JOB_STATE_SUCCEEDED", the result is accessible via job_status.dest.file_name. Download the raw byte stream, decode the lines, and map the outputs back using the original key.

Crucially, a successful batch job does not guarantee that every individual row succeeded. If a prompt triggered a safety block or malformed input schema, that specific line will output an error dictionary instead of a response block. Your ingestion parser must handle row-level exceptions gracefully.

import json
from google import genai

client = genai.Client()

# Retrieve destination file name from completed job
result_file_ref = job_status.dest.file_name
print(f"Downloading batch results from: {result_file_ref}")

file_bytes = client.files.download(file=result_file_ref)
result_lines = file_bytes.decode("utf-8").splitlines()

success_count = 0
error_count = 0

for line in result_lines:
    if not line.strip():
        continue
    record = json.loads(line)
    item_key = record.get("key")

    if "response" in record:
        success_count += 1
        # Extract candidate text
        candidate = record["response"]["candidates"][0]
        output_text = candidate["content"]["parts"][0]["text"]
        token_usage = record["response"].get("usageMetadata", {})
        
        # Parse structured classification payload
        parsed_payload = json.loads(output_text)
        print(f"[{item_key}] -> {parsed_payload} (Tokens: {token_usage.get('totalTokenCount')})")

    elif "error" in record:
        error_count += 1
        error_info = record["error"]
        print(f"[{item_key}] FAILED -> Code: {error_info.get('code')}, Message: {error_info.get('message')}")

print(f"\nProcessing Summary: {success_count} succeeded, {error_count} failed.")

365Finds Technical Assessment and Decision Matrix

At 365Finds, we see engineering teams frequently confuse Batch API with Context Caching. They serve radically different architecture patterns:

CriterionGemini Batch APIGemini Context Caching
Primary Use CaseOffline classification, benchmark suites, data labelingInteractive agents over fixed codebases, large PDF repos
Pricing BenefitFlat 50% discount on both prompt and candidate tokensUp to 75%-90% discount on cached input prefix tokens only
Latency ExpectationAsynchronous (minutes to 24 hours)Real-time synchronous (sub-second responses)
Prefix DependencyNone required; handles completely disparate promptsRequires large shared static prefix (typically >32,768 tokens)
Concurrency ImpactBypasses interactive RPM/TPM limitsSubject to standard interactive request quotas

Our Practical Recommendations

  1. Default to Gemini 2.5 Flash for Batch Classification: There is rarely a financial or accuracy justification to run routine text labeling or sentiment tagging on Gemini 2.5 Pro. Flash gives near-instant classification accuracy at pennies per hundred thousand rows, and halving that already low price with Batch API yields extraordinary ROI.
  2. Never Ignore the 48-Hour TTL: The Google Files API is a transport buffer, not an archive. Write your worker to immediately offload completed .jsonl outputs into Postgres, ClickHouse, or Parquet lakes.
  3. Use Explicit Schema Keys: Keep your key values semantic (e.g., ticket_{id}_{created_date}). When a run of 80,000 tickets contains 12 failures due to input validation or safety thresholds, you can isolate and re-queue only those specific failures without re-running the entire dataset.

References