Batch API

Gemini Batch API 的設計宗旨,是能以標準費用的 50% 非同步處理大量要求。目標處理時間為 24 小時,但大多數情況下,處理速度會更快。

如果工作規模龐大且不緊急,例如資料前處理或執行評估,且不需要立即取得回應,請使用 Batch API。

建立批次工作

您可以在 Batch API 中透過兩種方式提交要求:

  • 內嵌要求GenerateContentRequest 物件清單,直接包含在批次建立要求中。這適用於總要求大小不超過 20 MB 的較小批次。模型傳回的 outputinlineResponse 物件清單。
  • 輸入檔案JSON Lines (JSONL) 檔案,每行包含一個完整的 GenerateContentRequest 物件。建議您對較大的要求使用這個方法。模型傳回的輸出內容是 JSONL 檔案,每行都是 GenerateContentResponse 或狀態物件。

內嵌要求

如果要求數量不多,可以直接在 BatchGenerateContentRequest 中嵌入 GenerateContentRequest 物件。以下範例會使用內嵌要求呼叫 BatchGenerateContent 方法:

Python


from google import genai
from google.genai import types

client = genai.Client()

# A list of dictionaries, where each is a GenerateContentRequest
inline_requests = [
    {
        'contents': [{
            'parts': [{'text': 'Tell me a one-sentence joke.'}],
            'role': 'user'
        }]
    },
    {
        'contents': [{
            'parts': [{'text': 'Why is the sky blue?'}],
            'role': 'user'
        }]
    }
]

inline_batch_job = client.batches.create(
    model="gemini-3.5-flash",
    src=inline_requests,
    config={
        'display_name': "inlined-requests-job-1",
    },
)

print(f"Created batch job: {inline_batch_job.name}")

JavaScript


import {GoogleGenAI} from '@google/genai';

const ai = new GoogleGenAI({});

const