배치 API

배치 API

Gemini Batch API는 표준 비용의 50%로 대량의 요청을 비동기적으로 처리하도록 설계되었어요. 목표 처리 시간은 24시간이지만, 대부분의 경우 훨씬 더 빨라요.

즉각적인 응답이 필요하지 않은 대규모 비긴급 작업(예: 데이터 전처리, 평가 실행)에 Batch API를 사용하세요.

출처: 원문

본문

배치 작업 만들기

Batch API에서 요청을 제출하는 방법은 두 가지예요.

  • 인라인 요청: 배치 생성 요청에 직접 포함된 GenerateContentRequest 객체 목록. 총 요청 크기를 20MB 미만으로 유지하는 더 작은 배치에 적합해요. 모델이 반환하는 출력은 inlineResponse 객체 목록이에요.
  • 입력 파일: 각 줄이 완전한 GenerateContentRequest 객체를 포함하는 JSON Lines(JSONL) 파일. 더 큰 요청에 권장되는 방법이에요. 모델이 반환하는 출력은 각 줄이 GenerateContentResponse 또는 상태 객체인 JSONL 파일이에요.

인라인 요청

소수의 요청에 대해 BatchGenerateContentRequest 내에 GenerateContentRequest 객체를 직접 포함할 수 있어요. 다음 예시는 인라인 요청으로 BatchGenerateContent 메서드를 호출해요.

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}")
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);
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:batchGenerateContent \
-H "x-goog-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) 파일을 준비하세요. 이 파일의 각 줄은 사용자 정의 키와 유효한 GenerateContentRequest 객체인 request 객체를 포함하는 JSON 객체여야 해요. 사용자 정의 키는 응답에서 어떤 출력이 어떤 요청의 결과인지 나타내는 데 사용돼요. 예를 들어 키가 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 파일 내에서 다른 업로드된 파일을 참조할 수 있어요.

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}")
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 {
        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) {
        console.error(`An unexpected error occurred:`, error);
    }
}

// Write to a file.
writeBatchRequestsToFile(requests, filePath);

// Upload the file to the File API.
const uploadedFile = await ai.files.upload({file: 'my-batch-requests.jsonl', config: {
    mimeType: 'jsonl',
}});
console.log(uploadedFile.name);

다음 예시는 File API로 업로드된 입력 파일로 BatchGenerateContent 메서드를 호출해요.

from google import genai

# Assumes `uploaded_file` is the file object from the previous step
client = genai.Client()
file_batch_job = client.batches.create(
    model="gemini-3.8-flash",
    src=uploaded_file.name,
    config={
        'display_name': "file-upload-job-1",
    },
)

print(f"Created batch job: {file_batch_job.name}")
# Set the File ID taken from the upload response.
BATCH_INPUT_FILE='files/123456'
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:batchGenerateContent \
-X POST \
-H "x-goog-api-key: *** \
-H "Content-Type:application/json" \
-d "{
    'batch': {
        'display_name': 'my-batch-requests',
        'input_config': {
            'file_name': '${BATCH_INPUT_FILE}'
        }
    }
}"

배치 작업을 만들면 작업 이름이 반환돼요. 이 이름은 모니터링 및 작업 완료 후 결과 검색에 사용하세요.

다음은 작업 이름을 포함하는 출력 예시예요.

Created batch job from file: batches/123456789

배치 임베딩 지원

더 높은 처리량을 위해 Embeddings 모델과 상호작용하도록 Batch API를 사용할 수 있어요. 인라인 요청 또는 입력 파일로 임베딩 배치 작업을 만들려면 batches.create_embeddings API를 사용하고 임베딩 모델을 지정하세요.

from google import genai

client = genai.Client()

# Creating an embeddings batch job with an input file request:
file_job = client.batches.create_embeddings(
    model="gemini-embedding-2",
    src={'file_name': uploaded_batch_requests.name},
    config={'display_name': "Input embeddings batch"},
)

# Creating an embeddings batch job with an inline request:
batch_job = client.batches.create_embeddings(
    model="gemini-embedding-2",
    # For a predefined list of requests `inlined_requests`
    src={'inlined_requests': inlined_requests},
    config={'display_name': "Inlined embeddings batch"},
)
// Creating an embeddings batch job with an input file request:
let fileJob;
fileJob = await client.batches.createEmbeddings({
    model: 'gemini-embedding-2',
    src: {fileName: uploadedBatchRequests.name},
    config: {displayName: 'Input embeddings batch'},
});
console.log(`Created batch job: ${fileJob.name}`);

// Creating an embeddings batch job with an inline request:
let batchJob;
batchJob = await client.batches.createEmbeddings({
    model: 'gemini-embedding-2',
    // For a predefined a list of requests `inlinedRequests`
    src: {inlinedRequests: inlinedRequests},
    config: {displayName: 'Inlined embeddings batch'},
});
console.log(`Created batch job: ${batchJob.name}`);

요청 구성

표준 비배치 요청에서 사용할 모든 요청 구성은 포함할 수 있어요. 예를 들어 temperature, 시스템 지침을 지정하거나 다른 모달리티를 전달할 수 있어요. 다음 예시는 요청 중 하나에 시스템 지침이 포함된 인라인 요청을 보여줘요.

inline_requests_list = [
    {'contents': [{'parts': [{'text': 'Write a short poem about a cloud.'}]}]},
    {'contents': [{
        'parts': [{
            'text': 'Write a short poem about a cat.'
            }]
        }],
    'config': {
        'system_instruction': {'parts': [{'text': 'You are a cat. Your name is Neko.'}]}}
    }
]

마찬가지로 요청에 사용할 도구를 지정할 수 있어요. 다음 예시는 Google Search 도구를 활성화하는 요청을 보여줘요.

inlined_requests = [
{'contents': [{'parts': [{'text': 'Who won the euro 1998?'}]}]},
{'contents': [{'parts': [{'text': 'Who won the euro 2025?'}]}],
 'config':{'tools': [{'google_search': {}}]}}]

구조화된 출력을 지정할 수도 있어요. 다음 예시는 배치 요청에 지정하는 방법을 보여줘요.

import time
from google import genai
from pydantic import BaseModel, TypeAdapter

class Recipe(BaseModel):
    recipe_name: str
    ingredients: list[str]

client = genai.Client()

# A list of dictionaries, where each is a GenerateContentRequest
inline_requests = [
    {
        'contents': [{
            'parts': [{'text': 'List a few popular cookie recipes, and include the amounts of ingredients.'}],
            'role': 'user'
        }],
        'config': {
            'response_mime_type': 'application/json',
            'response_schema': list[Recipe]
        }
    },
    {
        'contents': [{
            'parts': [{'text': 'List a few popular gluten free cookie recipes, and include the amounts of ingredients.'}],
            'role': 'user'
        }],
        'config': {
            'response_mime_type': 'application/json',
            'response_schema': list[Recipe]
        }
    }
]

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

# wait for the job to finish
job_name = inline_batch_job.name
print(f"Polling status for job: {job_name}")

while True:
    batch_job_inline = client.batches.get(name=job_name)
    if batch_job_inline.state.name in ('JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED'):
        break
    print(f"Job not finished. Current state: {batch_job_inline.state.name}. Waiting 30 seconds...")
    time.sleep(30)

print(f"Job finished with state: {batch_job_inline.state.name}")

# print the response
for i, inline_response in enumerate(batch_job_inline.dest.inlined_responses, start=1):
    print(f"\n--- Response {i} ---")
    # Check for a successful response
    if inline_response.response:
        # The .text property is a shortcut to the generated text.
        print(inline_response.response.text)

작업 상태 모니터링

배치 작업 생성 시 얻은 작업 이름으로 상태를 폴링하세요. 배치 작업의 state 필드는 현재 상태를 나타내요. 배치 작업은 다음 상태 중 하나일 수 있어요.

  • JOB_STATE_PENDING: 작업이 생성되었고 서비스에서 처리되기를 기다리는 중.
  • JOB_STATE_RUNNING: 작업이 진행 중.
  • JOB_STATE_SUCCEEDED: 작업이 성공적으로 완료됨. 이제 결과를 검색할 수 있어요.
  • JOB_STATE_FAILED: 작업이 실패함. 오류 세부사항을 확인하세요.
  • JOB_STATE_CANCELLED: 사용자가 작업을 취소함.
  • JOB_STATE_EXPIRED: 48시간 이상 실행 중이거나 대기 중이어서 작업이 만료됨. 검색할 결과가 없어요. 작업을 다시 제출하거나 요청을 더 작은 배치로 분할할 수 있어요.

작업 완료를 확인하려면 작업 상태를 주기적으로 폴링할 수 있어요.

import time
from google import genai

client = genai.Client()

# Use the name of the job you want to check
# e.g., inline_batch_job.name from the previous step
job_name = "YOUR_BATCH_JOB_NAME"  # (e.g. 'batches/your-batch-id')
batch_job = client.batches.get(name=job_name)

completed_states = set([
    'JOB_STATE_SUCCEEDED',
    'JOB_STATE_FAILED',
    'JOB_STATE_CANCELLED',
    'JOB_STATE_EXPIRED',
])

print(f"Polling status for job: {job_name}")
batch_job = client.batches.get(name=job_name) # Initial get
while batch_job.state.name not in completed_states:
  print(f"Current state: {batch_job.state.name}")
  time.sleep(30) # Wait for 30 seconds before polling again
  batch_job = client.batches.get(name=job_name)

print(f"Job finished with state: {batch_job.state.name}")
if batch_job.state.name == 'JOB_STATE_FAILED':
    print(f"Error: {batch_job.error}")

폴링과 웹훅

폴링에 지쳤나요? Gemini는 이제 Webhooks를 지원해 비동기로 완료를 처리해요. GET / operations를 계속 호출하는 대신 batch.succeeded에 직접 구독해 비동기 또는 장기 실행 작업이 완료될 때 Gemini API가 실시간 알림을 서버로 푸시하게 할 수 있어요.

from google import genai

client = genai.Client()

webhook = client.webhooks.create(
    name="MyBatchWebhook",
    subscribed_events=["batch.succeeded", "batch.failed"],
    uri="https://my-api.com/gemini-callback",
)

print(f"Created webhook: {webhook.name}")
curl -X POST \
  "https://generativelanguage.googleapis.com/v1/webhooks?webhook_id=my-example-webhook-123" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: *** \
  -d '{
    "name": "My Example Webhook",
    "uri": "https://my-api.com/gemini-callback",
    "subscribed_events": ["batch.succeeded", "batch.failed"]
  }'

결과 검색

작업 상태가 배치 작업이 성공했음을 나타내면 결과가 response 필드에서 사용 가능해요. 기본적으로 배치 작업 결과는 영구 삭제되기 전 6주 동안 저장되고 다운로드할 수 있어요.

import json
from google import genai

client = genai.Client()

# Use the name of the job you want to check
# e.g., inline_batch_job.name from the previous step
job_name = "YOUR_BATCH_JOB_NAME"
batch_job = client.batches.get(name=job_name)

if batch_job.state.name == 'JOB_STATE_SUCCEEDED':

    # If batch job was created with a file
    if batch_job.dest and batch_job.dest.file_name:
        # Results are in a file
        result_file_name = batch_job.dest.file_name
        print(f"Results are in file: {result_file_name}")

        print("Downloading result file content...")
        file_content = client.files.download(file=result_file_name)
        # Process file_content (bytes) as needed
        print(file_content.decode('utf-8'))

    # If batch job was created with inline request
    # (for embeddings, use batch_job.dest.inlined_embed_content_responses)
    elif batch_job.dest and batch_job.dest.inlined_responses:
        # Results are inline
        print("Results are inline:")
        for i, inline_response in enumerate(batch_job.dest.inlined_responses):
            print(f"Response {i+1}:")
            if inline_response.response:
                # Accessing response, structure may vary.
                try:
                    print(inline_response.response.text)
                except AttributeError:
                    print(inline_response.response) # Fallback
            elif inline_response.error:
                print(f"Error: {inline_response.error}")
    else:
        print("No results found (neither file nor inline).")
else:
    print(f"Job did not succeed. Final state: {batch_job.state.name}")
    if batch_job.error:
        print(f"Error: {batch_job.error}")

배치 작업 나열

최근 배치 작업을 나열할 수 있어요.

batch_jobs = client.batches.list()

# Optional query config:
# batch_jobs = client.batches.list(config={'page_size': 5})

for batch_job in batch_jobs:
    print(batch_job)
curl https://generativelanguage.googleapis.com/v1beta/batches \
-H "x-goog-api-key: ***

배치 작업 취소

작업 이름으로 진행 중인 배치 작업을 취소할 수 있어요. 작업이 취소되면 새 요청 처리를 중단해요.

client.batches.cancel(name=batch_job_to_cancel.name)
BATCH_NAME="batches/123456" # Your batch job name

# Cancel the batch
curl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME:cancel \
-H "x-goog-api-key: ***

# Confirm that the status of the batch after cancellation is JOB_STATE_CANCELLED
curl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \
-H "x-goog-api-key: *** \
-H "Content-Type:application/json" 2> /dev/null | jq -r '.metadata.state'

배치 작업 삭제

작업 이름으로 기존 배치 작업을 삭제할 수 있어요. 작업이 삭제되면 새 요청 처리를 중단하고 배치 작업 목록에서 제거돼요.

client.batches.delete(name=batch_job_to_delete.name)
BATCH_NAME="batches/123456" # Your batch job name

# Delete the batch job
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME" \
-H "x-goog-api-key: ***

배치로 이미지 생성

Gemini Nano Banana를 사용하고 많은 이미지를 생성해야 한다면, 최대 24시간 처리 시간과 교환해 더 높은 요금 한도를 얻는 Batch API를 사용할 수 있어요. 소규모 요청(20MB 미만)에는 인라인 요청을, 대규모 배치에는 JSONL 입력 파일(이미지 생성에 권장)을 사용할 수 있어요.

이미지용 인라인 요청

import time
import base64
import json
from google import genai
from google.genai import types
from PIL import Image

client = genai.Client()

# 1. Create batch job with inline requests
inline_requests = [
    {
        'contents': [{'parts': [{'text': 'A big letter A surrounded by animals starting with the A letter'}]}],
        'config': {'response_modalities': ['TEXT', 'IMAGE']}
    },
    {
        'contents': [{'parts': [{'text': 'A big letter B surrounded by animals starting with the B letter'}]}],
        'config': {'response_modalities': ['TEXT', 'IMAGE']}
    }
]

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

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

# 2. Monitor job status
job_name = inline_batch_job.name
print(f"Polling status for job: {job_name}")

completed_states = set([
    'JOB_STATE_SUCCEEDED',
    'JOB_STATE_FAILED',
    'JOB_STATE_CANCELLED',
    'JOB_STATE_EXPIRED',
])

batch_job = client.batches.get(name=job_name) # Initial get
while batch_job.state.name not in completed_states:
  print(f"Current state: {batch_job.state.name}")
  time.sleep(10) # Wait for 10 seconds before polling again
  batch_job = client.batches.get(name=job_name)

print(f"Job finished with state: {batch_job.state.name}")

# 3. Retrieve results
if batch_job.state.name == 'JOB_STATE_SUCCEEDED':
    print("Results are inline:")
    for i, inline_response in enumerate(batch_job.dest.inlined_responses):
        print(f"Response {i+1}:")
        if inline_response.response:
            for part in inline_response.response.candidates[0].content.parts:
                if part.text:
                    print(part.text)
                elif part.inline_data:
                    print(f"Image mime type: {part.inline_data.mime_type}")
                    image = part.as_image()
                    image.save(f"image_{i+1}.png")
        elif inline_response.error:
            print(f"Error: {inline_response.error}")
elif batch_job.state.name == 'JOB_STATE_FAILED':
    print(f"Error: {batch_job.error}")

이미지용 입력 파일

import json
import time
import base64
from google import genai
from google.genai import types
from PIL import Image

client = genai.Client()

# 1. Create and upload file
file_name = "my-batch-image-requests.jsonl"
with open(file_name, "w") as f:
    requests = [
        {"key": "request-1", "request": {"contents": [{"parts": [{"text": "A big letter A surrounded by animals starting with the A letter"}]}], "generation_config": {"responseModalities": ["TEXT", "IMAGE"]}}},
        {"key": "request-2", "request": {"contents": [{"parts": [{"text": "A big letter B surrounded by animals starting with the B letter"}]}], "generation_config": {"responseModalities": ["TEXT", "IMAGE"]}}}
    ]
    for req in requests:
        f.write(json.dumps(req) + "\n")

uploaded_file = client.files.upload(
    file=file_name,
    config=types.UploadFileConfig(display_name='my-batch-image-requests', mime_type='jsonl')
)
print(f"Uploaded file: {uploaded_file.name}")

# 2. Create batch job
file_batch_job = client.batches.create(
    model="gemini-3-pro-image-preview",
    src=uploaded_file.name,
    config={
        'display_name': "file-image-upload-job-1",
    },
)
print(f"Created batch job: {file_batch_job.name}")

# 3. Monitor job status
job_name = file_batch_job.name
print(f"Polling status for job: {job_name}")

completed_states = set([
    'JOB_STATE_SUCCEEDED',
    'JOB_STATE_FAILED',
    'JOB_STATE_CANCELLED',
    'JOB_STATE_EXPIRED',
])

batch_job = client.batches.get(name=job_name) # Initial get
while batch_job.state.name not in completed_states:
  print(f"Current state: {batch_job.state.name}")
  time.sleep(10) # Wait for 10 seconds before polling again
  batch_job = client.batches.get(name=job_name)

print(f"Job finished with state: {batch_job.state.name}")

# 4. Retrieve results
if batch_job.state.name == 'JOB_STATE_SUCCEEDED':
    result_file_name = batch_job.dest.file_name
    print(f"Results are in file: {result_file_name}")
    print("Downloading result file content...")
    file_content_bytes = client.files.download(file=result_file_name)
    file_content = file_content_bytes.decode('utf-8')
    # The result file is also a JSONL file. Parse and print each line.
    for line in file_content.splitlines():
      if line:
        parsed_response = json.loads(line)
        if 'response' in parsed_response and parsed_response['response']:
            for part in parsed_response['response']['candidates'][0]['content']['parts']:
              if part.get('text'):
                print(part['text'])
              elif part.get('inlineData'):
                print(f"Image mime type: {part['inlineData']['mimeType']}")
                data = base64.b64decode(part['inlineData']['data'])
        elif 'error' in parsed_response:
            print(f"Error: {parsed_response['error']}")
elif batch_job.state.name == 'JOB_STATE_FAILED':
    print(f"Error: {batch_job.error}")

기술적 세부사항

  • 지원 모델: Batch API는 다양한 Gemini 모델을 지원해요. 각 모델의 Batch API 지원은 Models 페이지를 참조하세요. Batch API의 지원 모달리티는 대화형(비배치) API에서 지원되는 것과 동일해요.
  • 가격: Batch API 사용은 해당 모델의 표준 대화형 API 비용의 50%로 책정돼요. 자세한 내용은 가격 페이지를 참조하세요. 이 기능의 요금 한도는 요금 한도 페이지를 참조하세요.
  • 서비스 수준 목표(SLO): 배치 작업은 24시간 처리 시간 내에 완료되도록 설계돼요. 크기와 현재 시스템 부하에 따라 많은 작업이 훨씬 더 빨리 완료될 수 있어요.
  • 캐싱: 컨텍스트 캐싱이 배치 요청에 지원돼요. 배치 내 개별 요청의 구성에서 cached_content 리소스 이름을 지정해 캐시된 콘텐츠를 재사용하세요. 배치의 요청이 캐시 히트를 일으키면 표준 컨텍스트 캐싱 요금을 지불해요.

모범 사례

  • 큰 요청에는 입력 파일 사용: 많은 요청의 경우 항상 파일 입력 방법을 사용해 관리성을 높이고 BatchGenerateContent 호출 자체의 요청 크기 한도 충돌을 피하세요. 입력 파일당 2GB 크기 한도가 있음에 유의하세요.
  • 오류 처리: 작업 완료 후 batchStats에서 failedRequestCount를 확인하세요. 파일 출력을 사용하는 경우 각 줄을 파싱해 GenerateContentResponse인지 해당 특정 요청의 오류를 나타내는 상태 객체인지 확인하세요. 전체 오류 코드 집합은 트러블슈팅 가이드를 참조하세요.
  • 작업을 한 번만 제출: 배치 작업 생성은 멱등이 아니에요. 같은 생성 요청을 두 번 보내면 두 개의 별도 배치 작업이 생성돼요.
  • 매우 큰 배치 분할: 목표 처리 시간은 24시간이지만 실제 처리 시간은 시스템 부하와 작업 크기에 따라 달라질 수 있어요. 큰 작업의 경우 중간 결과를 더 빨리 필요로 한다면 더 작은 배치로 나누는 것을 고려하세요.

다음 단계

더 알아보기 (Learn more)