Batch API

Gemini Batch API को, बड़ी संख्या में अनुरोधों को एसिंक्रोनस तरीके से प्रोसेस करने के लिए डिज़ाइन किया गया है. इसके लिए, सामान्य शुल्क का 50% लिया जाता है. हमारा लक्ष्य है कि हम 24 घंटे के अंदर जवाब दें. हालांकि, ज़्यादातर मामलों में हम इससे पहले ही जवाब दे देते हैं.

बड़े पैमाने पर किए जाने वाले ऐसे टास्क के लिए Batch API का इस्तेमाल करें जिन्हें तुरंत पूरा करना ज़रूरी नहीं है. जैसे, डेटा को पहले से प्रोसेस करना या ऐसे आकलन करना जिनके लिए तुरंत जवाब की ज़रूरत नहीं होती.

बैच जॉब बनाना

Batch API में अनुरोध सबमिट करने के दो तरीके हैं:

  • इनलाइन अनुरोध: यह GenerateContentRequest ऑब्जेक्ट की सूची होती है. इन्हें एक साथ कई अनुरोध करने के लिए बनाए गए अनुरोध में सीधे तौर पर शामिल किया जाता है. यह छोटे बैच के लिए सही है. इससे अनुरोध का कुल साइज़ 20 एमबी से कम रहता है. मॉडल से मिला आउटपुट, inlineResponse ऑब्जेक्ट की सूची होती है.
  • इनपुट फ़ाइल: यह JSON लाइन्स (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="models/gemini-2.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 GEMINI_API_KEY = process.env.GEMINI_API_KEY;

const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});

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-2.5-flash',
    src: inlinedRequests,
    config: {
        displayName: 'inlined-requests-job-1',
    }
});

console.log(response);

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"
                        }
                    }
                ]
            }
        }
    }
}'

इनपुट फ़ाइल

ज़्यादा अनुरोधों के लिए, JSON लाइंस (JSONL) फ़ाइल तैयार करें. इस फ़ाइल की हर लाइन में एक JSON ऑब्जेक्ट होना चाहिए. इसमें उपयोगकर्ता की तय की गई कुंजी और एक अनुरोध ऑब्जेक्ट होना चाहिए. अनुरोध एक मान्य GenerateContentRequest ऑब्जेक्ट होना चाहिए. उपयोगकर्ता की तय की गई कुंजी का इस्तेमाल जवाब में यह बताने के लिए किया जाता है कि कौनसा आउटपुट किस अनुरोध का नतीजा है. उदाहरण के लिए, request-1 के तौर पर तय की गई कुंजी वाले अनुरोध के जवाब में, कुंजी का वही नाम एनोटेट किया जाएगा.

इस फ़ाइल को File API का इस्तेमाल करके अपलोड किया जाता है. इनपुट फ़ाइल का ज़्यादा से ज़्यादा साइज़ 2 जीबी होना चाहिए.

यहां 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


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 GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});
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, 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);

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)

यहां दिए गए उदाहरण में, File API का इस्तेमाल करके अपलोड की गई इनपुट फ़ाइल के साथ BatchGenerateContent तरीके को कॉल किया गया है:

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}")

JavaScript

// Assumes `uploadedFile` is the file object from the previous step
const fileBatchJob = await ai.batches.create({
    model: 'gemini-2.5-flash',
    src: uploadedFile.name,
    config: {
        displayName: 'file-upload-job-1',
    }
});

console.log(fileBatchJob);

REST

# Set the File ID taken from the upload response.
BATCH_INPUT_FILE='files/123456'
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': {
            'file_name': '${BATCH_INPUT_FILE}'
        }
    }
}"

बैच जॉब बनाने पर, आपको जॉब का नाम मिलेगा. इस नाम का इस्तेमाल, नौकरी के स्टेटस की मॉनिटरिंग करने के साथ-साथ, नौकरी पूरी होने के बाद नतीजे पाने के लिए करें.

यहां नौकरी के नाम वाला एक उदाहरण दिया गया है:


Created batch job from file: batches/123456789

एक साथ कई वीडियो एम्बेड करने की सुविधा

ज़्यादा थ्रूपुट के लिए, Embeddings मॉडल के साथ इंटरैक्ट करने के लिए, Batch API का इस्तेमाल किया जा सकता है. इनलाइन अनुरोधों या इनपुट फ़ाइलों का इस्तेमाल करके, एम्बेडिंग का बैच जॉब बनाने के लिए, batches.create_embeddings एपीआई का इस्तेमाल करें. साथ ही, एम्बेडिंग मॉडल के बारे में बताएं.

Python

# Creating an embeddings batch job with an input file request:
file_job = client.batches.create_embeddings(
    model="gemini-embedding-001",
    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-001",
    # For a predefined list of requests `inlined_requests`
    src={'inlined_requests': inlined_requests},
    config={'display_name': "Inlined embeddings batch"},
)

JavaScript

// Creating an embeddings batch job with an input file request:
let fileJob;
fileJob = await client.batches.createEmbeddings({
    model: 'gemini-embedding-001',
    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-001',
    // For a predefined a list of requests `inlinedRequests`
    src: {inlinedRequests: inlinedRequests},
    config: {displayName: 'Inlined embeddings batch'},
});
console.log(`Created batch job: ${batchJob.name}`);

ज़्यादा उदाहरणों के लिए, Batch API कुकबुक में Embeddings सेक्शन पढ़ें.

कॉन्फ़िगरेशन का अनुरोध करना

इसमें, अनुरोध से जुड़े उन सभी कॉन्फ़िगरेशन को शामिल किया जा सकता है जिनका इस्तेमाल स्टैंडर्ड नॉन-बैच अनुरोध में किया जाता है. उदाहरण के लिए, तापमान, सिस्टम के निर्देश या अन्य मोडैलिटी भी तय की जा सकती हैं. यहां दिए गए उदाहरण में, एक इनलाइन अनुरोध दिखाया गया है. इसमें अनुरोधों में से किसी एक के लिए सिस्टम निर्देश शामिल है:

Python

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.'}]}}
]

JavaScript

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

इसी तरह, किसी अनुरोध के लिए इस्तेमाल किए जाने वाले टूल के बारे में बताया जा सकता है. यहां दिए गए उदाहरण में, Google Search टूल को चालू करने का अनुरोध दिखाया गया है:

Python

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

JavaScript

inlineRequestsList = [
    {contents: [{parts: [{text: 'Who won the euro 1998?'}]}]},
    {contents: [{parts: [{text: 'Who won the euro 2025?'}]}], tools: [{googleSearch: {}}]}
]

स्ट्रक्चर्ड आउटपुट भी तय किया जा सकता है. यहां दिए गए उदाहरण में, बैच अनुरोधों के लिए जानकारी देने का तरीका बताया गया है.

Python

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, 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)

JavaScript


import {GoogleGenAI, Type} from '@google/genai';
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;

const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});

const inlinedRequests = [
    {
        contents: [{
            parts: [{text: 'List a few popular cookie recipes, and include the amounts of ingredients.'}],
            role: 'user'
        }],
        config: {
            responseMimeType: 'application/json',
            responseSchema: {
            type: Type.ARRAY,
            items: {
                type: Type.OBJECT,
                properties: {
                'recipeName': {
                    type: Type.STRING,
                    description: 'Name of the recipe',
                    nullable: false,
                },
                'ingredients': {
                    type: Type.ARRAY,
                    items: {
                    type: Type.STRING,
                    description: 'Ingredients of the recipe',
                    nullable: false,
                    },
                },
                },
                required: ['recipeName'],
            },
            },
        }
    },
    {
        contents: [{
            parts: [{text: 'List a few popular gluten free cookie recipes, and include the amounts of ingredients.'}],
            role: 'user'
        }],
        config: {
            responseMimeType: 'application/json',
            responseSchema: {
            type: Type.ARRAY,
            items: {
                type: Type.OBJECT,
                properties: {
                'recipeName': {
                    type: Type.STRING,
                    description: 'Name of the recipe',
                    nullable: false,
                },
                'ingredients': {
                    type: Type.ARRAY,
                    items: {
                    type: Type.STRING,
                    description: 'Ingredients of the recipe',
                    nullable: false,
                    },
                },
                },
                required: ['recipeName'],
            },
            },
        }
    }
]

const inlinedBatchJob = await ai.batches.create({
    model: 'gemini-2.5-flash',
    src: inlinedRequests,
    config: {
        displayName: 'inlined-requests-job-1',
    }
});

मॉनिटरिंग जॉब की स्थिति

बैच जॉब बनाते समय मिले ऑपरेशन के नाम का इस्तेमाल करके, उसकी स्थिति के बारे में जानकारी पाएं. बैच जॉब के स्टेट फ़ील्ड में, उसकी मौजूदा स्थिति दिखेगी. बैच जॉब की स्थिति इनमें से कोई एक हो सकती है:

  • JOB_STATE_PENDING: जॉब बना दी गई है और सेवा के ज़रिए प्रोसेस होने का इंतज़ार कर रही है.
  • JOB_STATE_RUNNING: जॉब चल रही है.
  • JOB_STATE_SUCCEEDED: जॉब पूरा हो गया है. अब नतीजे वापस लाए जा सकते हैं.
  • JOB_STATE_FAILED: जॉब पूरा नहीं हो सका. ज़्यादा जानकारी के लिए, गड़बड़ी की जानकारी देखें.
  • JOB_STATE_CANCELLED: उपयोगकर्ता ने जॉब रद्द कर दी है.
  • JOB_STATE_EXPIRED: यह जॉब इसलिए खत्म हो गई है, क्योंकि यह 48 घंटे से ज़्यादा समय से चल रही थी या इसकी प्रोसेस पूरी नहीं हुई थी. इस जॉब के लिए कोई नतीजा नहीं मिलेगा. आपके पास नौकरी का अनुरोध फिर से सबमिट करने का विकल्प है. इसके अलावा, अनुरोधों को छोटे-छोटे बैच में बांटा जा सकता है.

काम पूरा हुआ है या नहीं, यह देखने के लिए समय-समय पर जॉब स्टेटस को पोल किया जा सकता है.

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}")

JavaScript

// Use the name of the job you want to check
// e.g., inlinedBatchJob.name from the previous step
let batchJob;
const completedStates = new Set([
    'JOB_STATE_SUCCEEDED',
    'JOB_STATE_FAILED',
    'JOB_STATE_CANCELLED',
    'JOB_STATE_EXPIRED',
]);

try {
    batchJob = await ai.batches.get({name: inlinedBatchJob.name});
    while (!completedStates.has(batchJob.state)) {
        console.log(`Current state: ${batchJob.state}`);
        // Wait for 30 seconds before polling again
        await new Promise(resolve => setTimeout(resolve, 30000));
        batchJob = await client.batches.get({ name: batchJob.name });
    }
    console.log(`Job finished with state: ${batchJob.state}`);
    if (batchJob.state === 'JOB_STATE_FAILED') {
        // The exact structure of `error` might vary depending on the SDK
        // This assumes `error` is an object with a `message` property.
        console.error(`Error: ${batchJob.state}`);
    }
} catch (error) {
    console.error(`An error occurred while polling job ${batchJob.name}:`, error);
}

नतीजे वापस लाए जा रहे हैं

जब जॉब की स्थिति से पता चलता है कि आपका बैच जॉब पूरा हो गया है, तब नतीजे response फ़ील्ड में उपलब्ध होते हैं.

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
    # (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}")

JavaScript

// Use the name of the job you want to check
// e.g., inlinedBatchJob.name from the previous step
const jobName = "YOUR_BATCH_JOB_NAME"

let batchJob;
try {
    batchJob = await ai.batches.get({ name: jobName });

    if (batchJob.state === 'JOB_STATE_SUCCEEDED') {
        // If batch job was created with a file destination
        if (batchJob.dest && batchJob.dest.file_name) {
            const resultFileName = batchJob.dest.file_name;
            console.log(`Results are in file: ${resultFileName}`);

            console.log("Downloading result file content...");
            const fileContentBuffer = await ai.files.download({ file: resultFileName });
            // Process fileContentBuffer (Buffer) as needed
            console.log(fileContentBuffer.toString('utf-8'));
        }

        // If batch job was created with inline responses
        else if (batchJob.dest && batchJob.dest.inlined_responses) {
            console.log("Results are inline:");
            for (let i = 0; i < batchJob.dest.inlined_responses.length; i++) {
                const inlineResponse = batchJob.dest.inlined_responses[i];
                console.log(`Response ${i + 1}:`);
                if (inlineResponse.response) {
                    // Accessing response, structure may vary.
                    if (inlineResponse.response.text !== undefined) {
                        console.log(inlineResponse.response.text);
                    } else {
                        console.log(inlineResponse.response); // Fallback
                    }
                } else if (inlineResponse.error) {
                    console.error(`Error: ${inlineResponse.error}`);
                }
            }
        } else {
            console.log("No results found (neither file nor inline).");
        }
    } else {
        console.log(`Job did not succeed. Final state: ${batchJob.state}`);
        if (batchJob.error) {
            console.error(`Error: ${typeof batchJob.error === 'string' ? batchJob.error : batchJob.error.message || JSON.stringify(batchJob.error)}`);
        }
    }
} catch (error) {
    console.error(`An error occurred while processing job ${jobName}:`, 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

बैच जॉब रद्द करना

नाम का इस्तेमाल करके, चालू बैच जॉब को रद्द किया जा सकता है. जब किसी नौकरी को रद्द किया जाता है, तो वह नए अनुरोधों को प्रोसेस करना बंद कर देती है.

Python

# Cancel a batch job
client.batches.cancel(name=batch_job_to_cancel.name)

JavaScript

await ai.batches.cancel({name: batchJobToCancel.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'

बैच जॉब मिटाना

नाम का इस्तेमाल करके, किसी मौजूदा बैच जॉब को मिटाया जा सकता है. किसी जॉब को मिटाने पर, वह नए अनुरोधों को प्रोसेस करना बंद कर देती है. साथ ही, उसे बैच जॉब की सूची से हटा दिया जाता है.

Python

# Delete a batch job
client.batches.delete(name=batch_job_to_delete.name)

JavaScript

await ai.batches.delete({name: batchJobToDelete.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"

तकनीकी जानकारी

  • इन मॉडल के साथ काम करता है: Batch API, Gemini के कई मॉडल के साथ काम करता है. हर मॉडल के लिए, Batch API की सुविधा के बारे में जानने के लिए, मॉडल पेज पर जाएं. बैच एपीआई के लिए, इस्तेमाल की जा सकने वाली सुविधाएं वही हैं जो इंटरैक्टिव (या नॉन-बैच) एपीआई के लिए इस्तेमाल की जा सकती हैं.
  • कीमत: बैच एपीआई का इस्तेमाल करने पर, इंटरैक्टिव एपीआई के स्टैंडर्ड शुल्क का 50% शुल्क लगता है. यह शुल्क, उसी मॉडल के लिए लिया जाता है. ज़्यादा जानकारी के लिए, कीमत तय करने से जुड़ा पेज देखें. इस सुविधा के लिए, अनुरोध करने की दर की सीमाओं के बारे में जानने के लिए, अनुरोध करने की दर की सीमाओं वाला पेज देखें.
  • सेवा स्तर का उद्देश्य (एसएलओ): बैच जॉब को 24 घंटे के अंदर पूरा करने के लिए डिज़ाइन किया गया है. कई टास्क, उनके साइज़ और सिस्टम पर मौजूदा लोड के हिसाब से बहुत तेज़ी से पूरे हो सकते हैं.
  • कैश मेमोरी में सेव करना: बैच अनुरोधों के लिए, कॉन्टेक्स्ट को कैश मेमोरी में सेव करने की सुविधा चालू है. अगर आपके बैच में मौजूद किसी अनुरोध के लिए कैश मेमोरी का इस्तेमाल किया जाता है, तो कैश मेमोरी में सेव किए गए टोकन की कीमत, बैच से बाहर के एपीआई ट्रैफ़िक के लिए तय की गई कीमत के बराबर होती है.

सबसे सही तरीके

  • ज़्यादा अनुरोधों के लिए, इनपुट फ़ाइलों का इस्तेमाल करें: अगर आपको कई अनुरोध करने हैं, तो हमेशा फ़ाइल इनपुट करने के तरीके का इस्तेमाल करें. इससे अनुरोधों को बेहतर तरीके से मैनेज किया जा सकेगा. साथ ही, BatchGenerateContent कॉल के लिए अनुरोध के साइज़ की सीमाएं पूरी नहीं होंगी. ध्यान दें कि हर इनपुट फ़ाइल का साइज़ 2 जीबी से ज़्यादा नहीं होना चाहिए.
  • गड़बड़ी ठीक करना: कोई टास्क पूरा होने के बाद, failedRequestCount के लिए batchStats देखें. अगर फ़ाइल आउटपुट का इस्तेमाल किया जा रहा है, तो हर लाइन को पार्स करें. इससे यह पता चलेगा कि वह GenerateContentResponse है या स्टेटस ऑब्जेक्ट है, जो उस खास अनुरोध के लिए गड़बड़ी दिखाता है. गड़बड़ी कोड की पूरी सूची देखने के लिए, समस्या हल करने से जुड़ी गाइड देखें.
  • जॉब एक बार सबमिट करें: बैच जॉब बनाने की प्रोसेस, एक जैसी नहीं होती. अगर आपने एक ही अनुरोध को दो बार भेजा है, तो दो अलग-अलग बैच जॉब बनाए जाएंगे.
  • बहुत बड़े बैच को छोटे-छोटे बैच में बांटें: टारगेट टर्नअराउंड समय 24 घंटे है. हालांकि, सिस्टम लोड और जॉब के साइज़ के आधार पर, प्रोसेसिंग में लगने वाला समय अलग-अलग हो सकता है. अगर बड़े जॉब के बीच के नतीजे जल्द चाहिए, तो उन्हें छोटे-छोटे बैच में बांटें.

आगे क्या करना है

  • ज़्यादा उदाहरणों के लिए, Batch API नोटबुक देखें.
  • OpenAI के साथ काम करने वाली लेयर, Batch API के साथ काम करती है. OpenAI Compatibility पेज पर दिए गए उदाहरण पढ़ें.