Gemini Batch API는 대량의 요청을 표준 비용의 50% 로 비동기식으로 처리하도록 설계되었습니다. 목표 처리 시간은 24시간이지만 대부분의 경우 훨씬 빠릅니다.
데이터 전처리 또는 즉각적인 응답이 필요하지 않은 평가 실행과 같은 대규모의 긴급하지 않은 작업에 Batch API를 사용하세요.
일괄 작업 만들기
Batch API에서 요청을 제출하는 방법에는 두 가지가 있습니다.
- 인라인 요청: 일괄 생성 요청에 직접 포함된
GenerateContentRequest객체 목록입니다. 총 요청 크기를 20MB 미만으로 유지하는 소규모 일괄 처리에 적합합니다. 모델에서 반환되는 출력 은inlineResponse객체 목록입니다. - 입력 파일: 각 줄에 완전한
GenerateContentRequest객체가 포함된 JSON Lines (JSONL) 파일입니다. 이 메서드는 대규모 요청에 권장됩니다. 모델에서 반환되는 출력 은 각 줄이GenerateContentResponse또는 상태 객체인 JSONL 파일입니다.
인라인 요청
요청 수가 적은 경우
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.8-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.8-flash',
src: inlinedRequests,
config: {
displayName: 'inlined-requests-job-1',
}
});
console.log(response);
자바
import java.util.Arrays;
import com.google.genai.Client;
import com.google.genai.types.BatchJob;
import com.google.genai.types.BatchJobSource;
import com.google.genai.types.Content;
import com.google.genai.types.CreateBatchJobConfig;
import com.google.genai.types.InlinedRequest;
import com.google.genai.types.Part;
import java.util.List;
Client client = new Client();
// A list of InlinedRequest objects
List<InlinedRequest> inlineRequests =
Arrays.asList(
InlinedRequest.builder()
.contents(
Arrays.asList(
Content.builder()
.role("user")
.parts(Arrays.asList(Part.fromText("Tell me a one-sentence joke.")))
.build()))
.build(),
InlinedRequest.builder()
.contents(
Arrays.asList(
Content.builder()
.role("user")
.parts(Arrays.asList(Part.fromText("Why is the sky blue?")))
.build()))
.build());
BatchJobSource src = BatchJobSource.builder().inlinedRequests(inlineRequests).build();
CreateBatchJobConfig config =
CreateBatchJobConfig.builder().displayName("inlined-requests-job-1").build();
BatchJob inlineBatchJob = client.batches.create("gemini-3.8-flash", src, config);
System.out.println("Created batch job: " + inlineBatchJob.name().orElse(""));
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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) => {
console.error(`Error writing to file ${filePath}:`, err);
});