Gemini Batch API נועד לעבד נפחים גדולים של בקשות באופן אסינכרוני ב50% מהעלות הרגילה. זמן הטיפול הממוצע הוא 24 שעות, אבל ברוב המקרים הוא קצר יותר.
משתמשים ב-Batch API למשימות לא דחופות בהיקף גדול, כמו עיבוד מוקדם של נתונים או הפעלת הערכות שלא נדרש עבורן מענה מיידי.
יצירת משימה באצווה
יש שתי דרכים לשלוח בקשות ב-Batch API:
- בקשות מוטבעות: רשימה של אובייקטים
GenerateContentRequestשכלולים ישירות בבקשה ליצירת אצווה. האפשרות הזו מתאימה למנות קטנות יותר שבהן הגודל הכולל של הבקשה הוא פחות מ-20MB. הפלט שמוחזר מהמודל הוא רשימה של אובייקטים מסוגinlineResponse. - קובץ קלט: קובץ JSON Lines (JSONL) שבו כל שורה מכילה אובייקט
GenerateContentRequestמלא. השיטה הזו מומלצת לבקשות גדולות יותר. הפלט שמוחזר מהמודל הוא קובץ JSONL שבו כל שורה היאGenerateContentResponseאו אובייקט סטטוס.
בקשות מוטמעות
אם מדובר במספר קטן של בקשות, אפשר להטמיע ישירות את האובייקטים GenerateContentRequest בתוך BatchGenerateContentRequest. בדוגמה הבאה מפעילים את השיטה 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 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"
}
}
]
}
}
}
}'
קובץ קלט
לגבי קבוצות גדולות יותר של בקשות, צריך להכין קובץ JSON Lines (JSONL). כל שורה בקובץ הזה חייבת להיות אובייקט JSON שמכיל מפתח שהוגדר על ידי המשתמש ואובייקט בקשה, כאשר הבקשה היא אובייקט GenerateContentRequest תקין. המפתח שמוגדר על ידי המשתמש משמש בתשובה כדי לציין איזו תוצאה היא התוצאה של איזו בקשה. לדוגמה, אם הבקשה עם המפתח מוגדרת כ-request-1, התשובה תסומן באותו שם מפתח.
הקובץ הזה מועלה באמצעות File API. גודל הקובץ המקסימלי המותר לקובץ קלט הוא 2GB.
הנה דוגמה לקובץ JSONL. אפשר לשמור אותו בקובץ בשם 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?"}]}]}}
בדומה לבקשות מוטבעות, אפשר לציין פרמטרים אחרים כמו הוראות מערכת, כלים או הגדרות אחרות בכל בקשת JSON.
אפשר להעלות את הקובץ הזה באמצעות File API, כמו בדוגמה הבאה. אם אתם עובדים עם קלט רב-אופני, אתם יכולים להפנות לקבצים אחרים שהועלו בקובץ 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)