ব্যাচ API

জেমিনি ব্যাচ এপিআই স্ট্যান্ডার্ড খরচের ৫০% হারে অ্যাসিঙ্ক্রোনাসভাবে বৃহৎ পরিমাণ অনুরোধ প্রক্রিয়া করার জন্য ডিজাইন করা হয়েছে। লক্ষ্যমাত্রা নির্ধারণের সময় ২৪ ঘন্টা, তবে বেশিরভাগ ক্ষেত্রে এটি অনেক দ্রুত।

ডেটা প্রি-প্রসেসিং বা চলমান মূল্যায়নের মতো বৃহৎ, অ-জরুরি কাজের জন্য ব্যাচ API ব্যবহার করুন যেখানে তাৎক্ষণিক প্রতিক্রিয়ার প্রয়োজন হয় না।

একটি ব্যাচ জব তৈরি করা হচ্ছে

Batch API-তে আপনার অনুরোধ জমা দেওয়ার দুটি উপায় আছে:

  • ইনলাইন রিকোয়েস্ট : আপনার ব্যাচ তৈরির অনুরোধে সরাসরি অন্তর্ভুক্ত GenerateContentRequest অবজেক্টের একটি তালিকা। এটি ছোট ব্যাচের জন্য উপযুক্ত যেখানে মোট রিকোয়েস্টের আকার 20MB এর নিচে থাকে। মডেল থেকে ফিরে আসা আউটপুট হল inlineResponse অবজেক্টের একটি তালিকা।
  • ইনপুট ফাইল : একটি JSON লাইন (JSONL) ফাইল যেখানে প্রতিটি লাইনে একটি সম্পূর্ণ GenerateContentRequest অবজেক্ট থাকে। এই পদ্ধতিটি বৃহত্তর অনুরোধের জন্য সুপারিশ করা হয়। মডেল থেকে ফিরে আসা আউটপুট হল একটি JSONL ফাইল যেখানে প্রতিটি লাইন হয় একটি GenerateContentResponse অথবা একটি স্ট্যাটাস অবজেক্ট।

ইনলাইন অনুরোধ

অল্প সংখ্যক অনুরোধের জন্য, আপনি সরাসরি আপনার 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="models/gemini-2.5-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 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);

বিশ্রাম

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 Lines (JSONL) ফাইল প্রস্তুত করুন। এই ফাইলের প্রতিটি লাইনে একটি JSON অবজেক্ট থাকতে হবে যাতে একটি ব্যবহারকারী-সংজ্ঞায়িত কী এবং একটি অনুরোধ অবজেক্ট থাকবে, যেখানে অনুরোধটি একটি বৈধ GenerateContentRequest অবজেক্ট। প্রতিক্রিয়ায় ব্যবহারকারী-সংজ্ঞায়িত কী ব্যবহার করা হয় কোন আউটপুটটি কোন অনুরোধের ফলাফল তা নির্দেশ করার জন্য। উদাহরণস্বরূপ, request-1 হিসাবে সংজ্ঞায়িত কী সহ অনুরোধের প্রতিক্রিয়া একই কী নামে টীকাযুক্ত হবে।

এই ফাইলটি ফাইল 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-এ সিস্টেম নির্দেশাবলী, সরঞ্জাম বা অন্যান্য কনফিগারেশনের মতো অন্যান্য পরামিতি নির্দিষ্ট করতে পারেন।

আপনি নিম্নলিখিত উদাহরণে দেখানো ফাইল 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 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);

বিশ্রাম

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 পদ্ধতিকে কল করে:

পাইথন

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-2.5-flash",
    src=uploaded_file.name,
    config={
        'display_name': "file-upload-job-1",
    },
)

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

জাভাস্ক্রিপ্ট

// 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);

বিশ্রাম

# 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

ব্যাচ এম্বেডিং সমর্থন

উচ্চতর থ্রুপুটের জন্য আপনি এম্বেডিং মডেলের সাথে ইন্টারঅ্যাক্ট করতে ব্যাচ 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-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"},
)

জাভাস্ক্রিপ্ট

// 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}`);

আরও উদাহরণের জন্য ব্যাচ এপিআই কুকবুকের এম্বেডিং বিভাগটি পড়ুন।

কনফিগারেশনের অনুরোধ করুন

আপনি একটি স্ট্যান্ডার্ড নন-ব্যাচ অনুরোধে আপনার ব্যবহৃত যেকোনো অনুরোধ কনফিগারেশন অন্তর্ভুক্ত করতে পারেন। উদাহরণস্বরূপ, আপনি তাপমাত্রা, সিস্টেম নির্দেশাবলী নির্দিষ্ট করতে পারেন অথবা এমনকি অন্যান্য পদ্ধতিতেও পাস করতে পারেন। নিম্নলিখিত উদাহরণটি একটি উদাহরণ ইনলাইন অনুরোধ দেখায় যাতে অনুরোধগুলির একটির জন্য একটি সিস্টেম নির্দেশ রয়েছে:

পাইথন

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

জাভাস্ক্রিপ্ট

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

একইভাবে একটি অনুরোধের জন্য ব্যবহারযোগ্য সরঞ্জামগুলি নির্দিষ্ট করতে পারে। নিম্নলিখিত উদাহরণটি এমন একটি অনুরোধ দেখায় যা Google অনুসন্ধান সরঞ্জাম সক্ষম করে:

পাইথন

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

জাভাস্ক্রিপ্ট

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

আপনি স্ট্রাকচার্ড আউটপুটও নির্দিষ্ট করতে পারেন। নিম্নলিখিত উদাহরণটি আপনার ব্যাচ অনুরোধগুলির জন্য কীভাবে নির্দিষ্ট করবেন তা দেখায়।

পাইথন

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

জাভাস্ক্রিপ্ট


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 : কাজটি ৪৮ ঘন্টারও বেশি সময় ধরে চলমান বা মুলতুবি থাকার কারণে মেয়াদ শেষ হয়ে গেছে। কাজটি পুনরুদ্ধারের জন্য কোনও ফলাফল পাওয়া যাবে না। আপনি আবার কাজটি জমা দেওয়ার চেষ্টা করতে পারেন অথবা অনুরোধগুলিকে ছোট ছোট ব্যাচে ভাগ করে নিতে পারেন।

আপনি কাজের সমাপ্তি পরীক্ষা করার জন্য পর্যায়ক্রমে কাজের অবস্থা পোল করতে পারেন।

পাইথন

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

জাভাস্ক্রিপ্ট

// 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 ক্ষেত্রে পাওয়া যাবে।

পাইথন

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

জাভাস্ক্রিপ্ট

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

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

    if (batchJob.state === 'JOB_STATE_SUCCEEDED') {
        console.log('Found completed batch:', batchJob.displayName);
        console.log(batchJob);

        // If batch job was created with a file destination
        if (batchJob.dest?.fileName) {
            const resultFileName = batchJob.dest.fileName;
            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?.inlinedResponses) {
            console.log("Results are inline:");
            for (let i = 0; i < batchJob.dest.inlinedResponses.length; i++) {
                const inlineResponse = batchJob.dest.inlinedResponses[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}`);
                }
            }
        }

        // If batch job was an embedding batch with inline responses
        else if (batchJob.dest?.inlinedEmbedContentResponses) {
            console.log("Embedding results found inline:");
            for (let i = 0; i < batchJob.dest.inlinedEmbedContentResponses.length; i++) {
                const inlineResponse = batchJob.dest.inlinedEmbedContentResponses[i];
                console.log(`Response ${i + 1}:`);
                if (inlineResponse.response) {
                    console.log(inlineResponse.response);
                } 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);
}

বিশ্রাম

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

একটি ব্যাচ জব বাতিল করা হচ্ছে

আপনি একটি চলমান ব্যাচ জব এর নাম ব্যবহার করে বাতিল করতে পারেন। যখন একটি জব বাতিল করা হয়, তখন এটি নতুন অনুরোধ প্রক্রিয়াকরণ বন্ধ করে দেয়।

পাইথন

from google import genai

client = genai.Client()

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

জাভাস্ক্রিপ্ট

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

একটি ব্যাচ কাজ মুছে ফেলা হচ্ছে

আপনি একটি বিদ্যমান ব্যাচ জব এর নাম ব্যবহার করে মুছে ফেলতে পারেন। যখন একটি জব মুছে ফেলা হয়, তখন এটি নতুন অনুরোধ প্রক্রিয়াকরণ বন্ধ করে দেয় এবং ব্যাচ জবের তালিকা থেকে সরিয়ে ফেলা হয়।

পাইথন

from google import genai

client = genai.Client()

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

জাভাস্ক্রিপ্ট

await ai.batches.delete({name: batchJobToDelete.name});

বিশ্রাম

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"

প্রযুক্তিগত বিবরণ

  • সমর্থিত মডেল: ব্যাচ API বিভিন্ন ধরণের জেমিনি মডেল সমর্থন করে। প্রতিটি মডেলের ব্যাচ API সমর্থনের জন্য মডেল পৃষ্ঠাটি দেখুন। ব্যাচ API এর জন্য সমর্থিত পদ্ধতিগুলি ইন্টারেক্টিভ (অথবা নন-ব্যাচ) API তে সমর্থিত পদ্ধতিগুলির মতোই।
  • মূল্য নির্ধারণ: সমতুল্য মডেলের জন্য ব্যাচ API ব্যবহারের মূল্য স্ট্যান্ডার্ড ইন্টারেক্টিভ API খরচের ৫০%। বিস্তারিত জানার জন্য মূল্য পৃষ্ঠাটি দেখুন। এই বৈশিষ্ট্যের জন্য হার সীমা সম্পর্কে বিস্তারিত জানার জন্য হার সীমা পৃষ্ঠাটি দেখুন।
  • সার্ভিস লেভেল অবজেক্টিভ (SLO): ব্যাচ জবগুলি 24 ঘন্টার মধ্যে সম্পন্ন করার জন্য ডিজাইন করা হয়েছে। অনেক কাজ তাদের আকার এবং বর্তমান সিস্টেম লোডের উপর নির্ভর করে অনেক দ্রুত সম্পন্ন হতে পারে।
  • ক্যাশিং: ব্যাচ অনুরোধের জন্য কনটেক্সট ক্যাশিং সক্ষম করা আছে। যদি আপনার ব্যাচের কোনও অনুরোধের ফলে ক্যাশে হিট হয়, তাহলে ক্যাশ করা টোকেনগুলির দাম নন-ব্যাচ API ট্র্যাফিকের মতোই হবে।

সেরা অনুশীলন

  • বড় অনুরোধের জন্য ইনপুট ফাইল ব্যবহার করুন: প্রচুর সংখ্যক অনুরোধের জন্য, আরও ভাল পরিচালনার জন্য এবং BatchGenerateContent কলের জন্য অনুরোধের আকারের সীমা অতিক্রম করা এড়াতে সর্বদা ফাইল ইনপুট পদ্ধতি ব্যবহার করুন। মনে রাখবেন যে প্রতি ইনপুট ফাইলে 2GB ফাইলের আকারের সীমা রয়েছে।
  • ত্রুটি পরিচালনা: কোনও কাজ সম্পন্ন হওয়ার পরে failedRequestCount জন্য batchStats পরীক্ষা করুন। যদি ফাইল আউটপুট ব্যবহার করেন, তাহলে প্রতিটি লাইন পার্স করে পরীক্ষা করুন যে এটি একটি GenerateContentResponse নাকি কোনও স্ট্যাটাস অবজেক্ট যা সেই নির্দিষ্ট অনুরোধের জন্য একটি ত্রুটি নির্দেশ করে। ত্রুটি কোডের সম্পূর্ণ সেটের জন্য সমস্যা সমাধানের নির্দেশিকা দেখুন।
  • একবার কাজ জমা দিন: একটি ব্যাচ জব তৈরি করা অকার্যকর। আপনি যদি একই তৈরির অনুরোধ দুবার পাঠান, তাহলে দুটি পৃথক ব্যাচ জব তৈরি হবে।
  • খুব বড় ব্যাচগুলিকে ভেঙে ফেলুন: যদিও টার্নঅ্যারাউন্ড সময় ২৪ ঘন্টা, প্রকৃত প্রক্রিয়াকরণ সময় সিস্টেম লোড এবং কাজের আকারের উপর নির্ভর করে পরিবর্তিত হতে পারে। বড় কাজের জন্য, যদি মধ্যবর্তী ফলাফলের প্রয়োজন হয় তবে সেগুলিকে ছোট ব্যাচে ভাগ করার কথা বিবেচনা করুন।

এরপর কি?