L'API Gemini Batch è progettata per elaborare grandi volumi di richieste in modo asincrono al 50% del costo standard. Il tempo di risposta target è di 24 ore, ma nella maggior parte dei casi è molto più rapido.
Utilizza l'API Batch per attività su larga scala e non urgenti, come la pre-elaborazione dei dati o l'esecuzione di valutazioni in cui non è richiesta una risposta immediata.
Creazione di un job batch
Esistono due modi per inviare le richieste nell'API Batch:
- Richieste inline: un elenco di oggetti
GenerateContentRequestinclusi direttamente nella richiesta di creazione batch. Questa opzione è adatta a batch più piccoli che mantengono le dimensioni totali della richiesta al di sotto di 20 MB. L'output restituito dal modello è un elenco di oggettiinlineResponse. - File di input: un file JSON Lines (JSONL)
in cui ogni riga contiene un oggetto
GenerateContentRequestcompleto. Questo metodo è consigliato per le richieste più grandi. L'output restituito dal modello è un file JSONL in cui ogni riga è un oggettoGenerateContentResponseo di stato.
Richieste inline
Per un numero ridotto di richieste, puoi incorporare direttamente gli oggetti
GenerateContentRequest
all'interno del tuo BatchGenerateContentRequest. L'esempio seguente chiama il metodo BatchGenerateContent con richieste inline:
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 inlinedRequests = [
{
contents: [{
parts: [{text: 'Tell me a one-sentence joke.'}],
role: 'user'
}]
},
{
contents: [{
parts: [{'text': 'Why is the sky blue?'}],
role: 'user'
}]
}
]
const response = await ai.batches.create({
model: 'gemini-3.5-flash',
src: inlinedRequests,
config: {
displayName: 'inlined-requests-job-1',
}
});
console.log(response);
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:batchGenerateContent \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-X POST \
-H "Content-Type:application/json" \
-d '{
"batch": {
"display_name": "my-batch-requests",
"input_config": {
"requests": {
"requests": [
{
"request": {"contents": [{"parts": [{"text": "Describe the process of photosynthesis."}]}]},
"metadata": {
"key": "request-1"
}
},
{
"request": {"contents": [{"parts": [{"text": "Describe the process of photosynthesis."}]}]},
"metadata": {
"key": "request-2"
}
}
]
}
}
}
}'
File di input
Per set di richieste più grandi, prepara un file JSON Lines (JSONL). Ogni riga di questo file deve essere un oggetto JSON contenente una chiave definita dall'utente e un oggetto richiesta, dove la richiesta è un oggetto GenerateContentRequest valido. La chiave definita dall'utente viene utilizzata nella risposta per indicare quale output è il risultato di quale richiesta. Ad esempio, la richiesta con la chiave definita come request-1
avrà la risposta annotata con lo stesso nome della chiave.
Questo file viene caricato utilizzando l'API File. La dimensione massima consentita per un file di input è 2 GB.
Di seguito è riportato un esempio di file JSONL. Puoi salvarlo in un file denominato my-batch-requests.json:
{"key": "request-1", "request": {"contents": [{"parts": [{"text": "Describe the process of photosynthesis."}]}], "generation_config": {"temperature": 0.7}}}
{"key": "request-2", "request": {"contents": [{"parts": [{"text": "What are the main ingredients in a Margherita pizza?"}]}]}}
Analogamente alle richieste inline, puoi specificare altri parametri come istruzioni di sistema, strumenti o altre configurazioni in ogni JSON della richiesta.
Puoi caricare questo file utilizzando l'API File come mostrato nell'esempio seguente. Se utilizzi l'input multimodale, puoi fare riferimento ad altri file caricati all'interno del file JSONL.
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}")
JavaScript
import {GoogleGenAI} from '@google/genai';
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from 'url';
const ai = new GoogleGenAI({});
const fileName = "my-batch-requests.jsonl";
// Define the requests
const 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?" }] }] } }
];
// Construct the full path to file
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filePath = path.join(__dirname, fileName); // __dirname is the directory of the current script
async function writeBatchRequestsToFile(requests, filePath) {
try {
// Use a writable stream for efficiency, especially with larger files.
const writeStream = fs.createWriteStream(filePath, { flags: 'w' });
writeStream.on('error', (err) => {
console.error(`Error writing to file ${filePath}:`, err);
});
for (const req of requests) {
writeStream.write(JSON.stringify(req) + '\n');
}
writeStream.end();
console.log(`Successfully wrote batch requests to ${filePath}`);
} catch (error) {
// This catch block is for errors that might occur before stream setup,
// stream errors are handled by the 'error' event.
console.error(`An unexpected error occurred:`, error);
}
}
// Write to a file.
writeBatchRequestsToFile(requests,