Gemini API Toplu İşlem Modu, büyük hacimli istekleri standart maliyetin% 50'si karşılığında eşzamansız olarak işlemek için tasarlanmıştır. Hedef işlem süresi 24 saattir ancak çoğu durumda bu süre çok daha kısadır.
Veri ön işleme veya acil yanıt gerektirmeyen değerlendirmeler çalıştırma gibi büyük ölçekli ve acil olmayan görevler için toplu modu kullanın.
Toplu iş oluşturma
Toplu modda isteklerinizi göndermenin iki yolu vardır:
- Satır İçi İstekler: Toplu oluşturma isteğinize doğrudan dahil edilen
GenerateContentRequest
nesnelerin listesi. Bu yöntem, toplam istek boyutunu 20 MB'ın altında tutan daha küçük gruplar için uygundur. Modelden döndürülen çıktı,inlineResponse
nesnelerinin listesidir. - Giriş Dosyası: Her satırın eksiksiz bir JSON Lines (JSONL) dosyası içerdiği
GenerateContentRequest
nesnesi. Bu yöntem, daha büyük istekler için önerilir. Modelden döndürülen çıktı, her satırınGenerateContentResponse
veya durum nesnesi olduğu bir JSONL dosyasıdır.
Satır içi istekler
Küçük bir istek grubu için GenerateContentRequest
nesnelerini doğrudan BatchGenerateContentRequest
içine yerleştirebilirsiniz. Aşağıdaki örnekte, satır içi isteklerle BatchGenerateContent
yöntemi çağrılıyor:
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="models/gemini-2.5-flash", src=inline_requests, config={ 'display_name': "inlined-requests-job-1", }, ) print(f"Created batch job: {inline_batch_job.name}")
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.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" } } ] } } } }'
Giriş dosyası
Daha büyük istek grupları için JSON Lines (JSONL) dosyası hazırlayın. Bu dosyadaki her satır, kullanıcı tanımlı bir anahtar ve bir istek nesnesi içeren bir JSON nesnesi olmalıdır. İstek, geçerli bir GenerateContentRequest
nesnesi olmalıdır. Kullanıcı tanımlı anahtar, hangi çıktının hangi isteğin sonucu olduğunu belirtmek için yanıtta kullanılır. Örneğin, request-1
olarak tanımlanan anahtara sahip isteklerin yanıtı aynı anahtar adıyla açıklama eklenmiş olarak döndürülür.
Bu dosya, File API kullanılarak yüklenir. Giriş dosyası için izin verilen maksimum dosya boyutu 2 GB'tır.
Aşağıda bir JSONL dosyası örneği verilmiştir. Dosyayı my-batch-requests.json
adlı bir dosyaya kaydedebilirsiniz:
{"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?"}]}]}}
Satır içi isteklerde olduğu gibi, her istek JSON'ında sistem talimatları, araçlar veya diğer yapılandırmalar gibi başka parametreler de belirtebilirsiniz.
Bu dosyayı, aşağıdaki örnekte gösterildiği gibi File API'yi kullanarak yükleyebilirsiniz. Çok formatlı girişle çalışıyorsanız JSONL dosyanızda yüklenen diğer dosyalara referans verebilirsiniz.
Python
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}")
REST
tmp_batch_input_file=batch_input.tmp echo -e '{"contents": [{"parts": [{"text": "Describe the process of photosynthesis."}]}], "generationConfig": {"temperature": 0.7}}\n{"contents": [{"parts": [{"text": "What are the main ingredients in a Margherita pizza?"}]}]}' > batch_input.tmp MIME_TYPE=$(file -b --mime-type "${tmp_batch_input_file}") NUM_BYTES=$(wc -c < "${tmp_batch_input_file}") DISPLAY_NAME=BatchInput tmp_header_file=upload-header.tmp # Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file. curl "https://generativelanguage.googleapis.com/upload/v1beta/files \ -D "${tmp_header_file}" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H "X-Goog-Upload-Protocol: resumable" \ -H "X-Goog-Upload-Command: start" \ -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \ -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \ -H "Content-Type: application/jsonl" \ -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r") rm "${tmp_header_file}" # Upload the actual bytes. curl "${upload_url}" \ -H "Content-Length: ${NUM_BYTES}" \ -H "X-Goog-Upload-Offset: 0" \ -H "X-Goog-Upload-Command: upload, finalize" \ --data-binary "@${tmp_batch_input_file}" 2> /dev/null > file_info.json file_uri=$(jq ".file.uri" file_info.json)
Aşağıdaki örnekte, File API kullanılarak yüklenen giriş dosyasıyla BatchGenerateContent
yöntemi çağrılıyor:
Python
# Assumes `uploaded_file` is the file object from the previous step file_batch_job = client.batches.create( model="gemini-2.5-flash", src=uploaded_file.name, config={ 'display_name': "file-upload-job-1", }, ) print(f"Created batch job: {file_batch_job.name}")
REST
BATCH_INPUT_FILE='files/123456' # File ID curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:batchGenerateContent \ -X POST \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H "Content-Type:application/json" \ -d "{ 'batch': { 'display_name': 'my-batch-requests', 'input_config': { 'requests': { 'file_name': ${BATCH_INPUT_FILE} } } } }"
Bir toplu iş oluşturduğunuzda iş adı döndürülür. Bu adı, işin durumunu izlemenin yanı sıra iş tamamlandıktan sonra sonuçları almak için kullanın.
Aşağıda, iş adı içeren bir çıkış örneği verilmiştir:
Created batch job from file: batches/123456789
Yapılandırma isteği
Standart toplu olmayan bir istekte kullanacağınız tüm istek yapılandırmalarını ekleyebilirsiniz. Örneğin, sıcaklığı, sistem talimatlarını belirtebilir veya başka yöntemler de kullanabilirsiniz. Aşağıdaki örnekte, isteklerden biri için sistem talimatı içeren bir satır içi istek örneği gösterilmektedir:
inline_requests_list = [ {'contents': [{'parts': [{'text': 'Write a short poem about a cloud.'}]}]}, {'contents': [{'parts': [{'text': 'Write a short poem about a cat.'}]}], 'system_instructions': {'parts': [{'text': 'You are a cat. Your name is Neko.'}]}} ]
Benzer şekilde, bir istek için kullanılacak araçları da belirtebilirsiniz. Aşağıdaki örnekte, Google Arama aracını etkinleştiren bir istek gösterilmektedir:
inline_requests_list = [ {'contents': [{'parts': [{'text': 'Who won the euro 1998?'}]}]}, {'contents': [{'parts': [{'text': 'Who won the euro 2025?'}]}], 'tools': [{'google_search ': {}}]} ]
Yapılandırılmış çıkış da belirtebilirsiniz. Aşağıdaki örnekte, toplu istekleriniz için nasıl belirteceğiniz gösterilmektedir.
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="models/gemini-2.5-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): print(f"\n--- Response {i+1} ---") # Check for a successful response if inline_response.response: # The .text property is a shortcut to the generated text. print(inline_response.response.text)
İş durumunu izleme
Durumunu yoklamak için toplu iş oluşturulurken alınan işlem adını kullanın. Toplu işin durum alanı, mevcut durumunu gösterir. Toplu işler aşağıdaki durumlardan birinde olabilir:
JOB_STATE_PENDING
: İş oluşturuldu ve hizmet tarafından işlenmeyi bekliyor.JOB_STATE_RUNNING
: İş devam ediyor.JOB_STATE_SUCCEEDED
: İş başarıyla tamamlandı. Artık sonuçları alabilirsiniz.JOB_STATE_FAILED
: İş başarısız oldu. Daha fazla bilgi için hata ayrıntılarını kontrol edin.JOB_STATE_CANCELLED
: İş, kullanıcı tarafından iptal edildi.JOB_STATE_EXPIRED
: İş, 48 saatten uzun süredir çalıştığı veya beklemede olduğu için süresi doldu. İşin alınacak sonucu olmayacak. İşi tekrar göndermeyi veya istekleri daha küçük gruplara bölmeyi deneyebilirsiniz.
Tamamlanıp tamamlanmadığını kontrol etmek için iş durumunu düzenli olarak sorgulayabilirsiniz.
Python
# 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}")
Sonuçlar alınıyor
İş durumu, toplu işinizin başarılı olduğunu gösterdiğinde sonuçlar response
alanında kullanılabilir.
Python
import json # 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 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}")
REST
BATCH_NAME="batches/123456" # Your batch job name curl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H "Content-Type:application/json" 2> /dev/null > batch_status.json if jq -r '.done' batch_status.json | grep -q "false"; then echo "Batch has not finished processing" fi batch_state=$(jq -r '.metadata.state' batch_status.json) if [[ $batch_state = "JOB_STATE_SUCCEEDED" ]]; then if [[ $(jq '.response | has("inlinedResponses")' batch_status.json) = "true" ]]; then jq -r '.response.inlinedResponses' batch_status.json exit fi responses_file_name=$(jq -r '.response.responsesFile' batch_status.json) curl https://generativelanguage.googleapis.com/download/v1beta/$responses_file_name:download?alt=media \ -H "x-goog-api-key: $GEMINI_API_KEY" 2> /dev/null elif [[ $batch_state = "JOB_STATE_FAILED" ]]; then jq '.error' batch_status.json elif [[ $batch_state == "JOB_STATE_CANCELLED" ]]; then echo "Batch was cancelled by the user" elif [[ $batch_state == "JOB_STATE_EXPIRED" ]]; then echo "Batch expired after 48 hours" fi
Toplu işi iptal etme
Devam eden bir toplu işi adını kullanarak iptal edebilirsiniz. Bir iş iptal edildiğinde yeni istekleri işlemeyi durdurur.
Python
# Cancel a batch job client.batches.cancel(name=batch_job_to_cancel.name)
REST
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: $GEMINI_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: $GEMINI_API_KEY" \ -H "Content-Type:application/json" 2> /dev/null | jq -r '.metadata.state'
Toplu işi silme
Mevcut bir toplu işi adını kullanarak silebilirsiniz. Bir iş silindiğinde yeni isteklerin işlenmesi durdurulur ve iş, toplu işler listesinden kaldırılır.
Python
# Delete a batch job client.batches.delete(name=batch_job_to_delete.name)
REST
BATCH_NAME="batches/123456" # Your batch job name # Delete the batch job curl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME:delete \ -H "x-goog-api-key: $GEMINI_API_KEY"
Teknik ayrıntılar
- Desteklenen modeller: Toplu mod, çeşitli Gemini modellerini destekler. Her modelin toplu modu destekleme durumu için Modeller sayfası'na bakın. Toplu modda desteklenen yöntemler, etkileşimli (veya toplu olmayan mod) API'de desteklenenlerle aynıdır.
- Fiyatlandırma: Toplu mod kullanımı, eşdeğer model için standart etkileşimli API maliyetinin% 50'si olarak fiyatlandırılır. Ayrıntılar için fiyatlandırma sayfasına göz atın. Bu özelliğin sıklık sınırlarıyla ilgili ayrıntılar için sıklık sınırları sayfasına bakın.
- Hizmet düzeyi hedefi (SLO): Toplu işler, 24 saatlik bir işlem süresi içinde tamamlanacak şekilde tasarlanmıştır. Birçok iş, boyutuna ve mevcut sistem yüküne bağlı olarak çok daha hızlı tamamlanabilir.
- Önbelleğe alma: Toplu istekler için bağlam önbelleğe alma etkinleştirilir. Grubunuzdaki bir istek önbellek isabetiyle sonuçlanırsa önbelleğe alınan jetonlar, grup dışı mod trafiğiyle aynı şekilde fiyatlandırılır.
En iyi uygulamalar
- Büyük istekler için giriş dosyalarını kullanın: Çok sayıda istek için, daha iyi yönetilebilirlik sağlamak ve
BatchGenerateContent
çağrısının kendisiyle ilgili istek boyutu sınırlarına ulaşmamak amacıyla her zaman dosya girişi yöntemini kullanın. Giriş dosyası başına 2 GB dosya boyutu sınırı olduğunu unutmayın. - Hata işleme: Bir iş tamamlandıktan sonra
batchStats
içinfailedRequestCount
öğesini kontrol edin. Dosya çıkışı kullanıyorsanız her satırı ayrıştırarakGenerateContentResponse
olup olmadığını veya söz konusu istekte hata olduğunu belirten bir durum nesnesi olup olmadığını kontrol edin. Hata kodlarının tam listesi için sorun giderme kılavuzuna bakın. - İşleri bir kez gönderme: Toplu iş oluşturma işlemi, idempotent değildir. Aynı oluşturma isteğini iki kez gönderirseniz iki ayrı toplu iş oluşturulur.
- Çok büyük toplu işlemleri bölme: Hedef işlem süresi 24 saat olsa da gerçek işlem süresi sistem yüküne ve iş boyutuna bağlı olarak değişebilir. Büyük işlerde, ara sonuçlara daha erken ihtiyaç duyuluyorsa işleri daha küçük gruplara ayırmayı düşünebilirsiniz.
Sırada ne var?
Daha fazla örnek için toplu mod not defterine göz atın.