Flex inference

Gemini Flex API, अनुमान लगाने वाला टियर है. इसमें स्टैंडर्ड दरों की तुलना में 50% कम कीमत लगती है. हालांकि, इसमें जवाब मिलने में लगने वाला समय अलग-अलग हो सकता है. साथ ही, यह सबसे अच्छे तरीके से उपलब्ध होता है. इसे ऐसे वर्कलोड के लिए डिज़ाइन किया गया है जिनमें इंतज़ार का समय कम होता है. साथ ही, जिनमें सिंक्रोनस प्रोसेसिंग की ज़रूरत होती है, लेकिन स्टैंडर्ड एपीआई की रीयल-टाइम परफ़ॉर्मेंस की ज़रूरत नहीं होती.

Flex इस्तेमाल करने का तरीका

Flex टियर का इस्तेमाल करने के लिए, अनुरोध के मुख्य हिस्से में service_tier को flex के तौर पर सेट करें. इस फ़ील्ड को शामिल न करने पर, अनुरोधों के लिए डिफ़ॉल्ट रूप से स्टैंडर्ड टियर का इस्तेमाल किया जाता है.

Python

import google.genai as genai

client = genai.Client()

try:
    response = client.models.generate_content(
        model="gemini-3-flash-preview",
        contents="Analyze this dataset for trends...",
        config={'service_tier': 'flex'},
    )
    print(response.text)
except Exception as e:
    print(f"Flex request failed: {e}")

JavaScript

import {GoogleGenAI} from '@google/genai';

const ai = new GoogleGenAI({});

async function main() {
  try {
    const response = await ai.models.generateContent({
      model: "gemini-3-flash-preview",
      contents: "Analyze this dataset for trends...",
      config: { serviceTier: "flex" },
    });
    console.log(response.text);
  } catch (e) {
    console.log(`Flex request failed: ${e}`);
  }
}

await main();

ऐप पर जाएं

package main

import (
    "context"
    "fmt"
    "log"
    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    result, err := client.Models.GenerateContent(
        ctx,
        "gemini-3-flash-preview",
        genai.Text("Analyze this dataset for trends..."),
        &genai.GenerateContentConfig{
            ServiceTier: "flex",
        },
    )
    if err != nil {
        log.Printf("Flex request failed: %v", err)
        return
    }
    fmt.Println(result.Text())
}

REST

"https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "contents": [{
    "parts":[{"text": "Summarize the latest research on quantum computing."}]
  }],
  "service_tier": "FLEX"
}'

फ़्लेक्स इन्फ़रेंस कैसे काम करता है

Gemini Flex के अनुमान लगाने की सुविधा, स्टैंडर्ड एपीआई और Batch API के 24 घंटे के टर्नअराउंड के बीच के अंतर को कम करती है. यह ऑफ़-पीक समय में, "शेड की जा सकने वाली" कंप्यूट क्षमता का इस्तेमाल करता है. इससे बैकग्राउंड टास्क और क्रमवार वर्कफ़्लो के लिए, कम लागत वाला समाधान मिलता है.

सुविधा Flex प्राथमिकता स्टैंडर्ड बैच
कीमत 50% की छूट स्टैंडर्ड से 75 से 100% ज़्यादा फ़ुल टिकट 50% की छूट
लेटेंसी मिनट (1 से 15 मिनट का टारगेट) कम (सेकंड) सेकंड से मिनट 24 घंटे तक
भरोसेमंद होना सबसे अच्छी कोशिश (शेड किया जा सकता है) ज़्यादा (नहीं बदले जा सकने वाले) ज़्यादा / सामान्य से ज़्यादा ज़्यादा (थ्रूपुट के लिए)
इंटरफ़ेस सिंक्रोनस सिंक्रोनस सिंक्रोनस एसिंक्रोनस

मुख्य फ़ायदे

  • लागत कम होना: प्रोडक्शन के अलावा अन्य कामों के लिए, बैकग्राउंड एजेंट, और डेटा को बेहतर बनाने के लिए, लागत में काफ़ी बचत होती है.
  • इस्तेमाल करने में आसान: बैच ऑब्जेक्ट, जॉब आईडी या पोलिंग को मैनेज करने की ज़रूरत नहीं है. बस अपने मौजूदा अनुरोधों में एक पैरामीटर जोड़ें.
  • सिंक्रोनस वर्कफ़्लो: यह क्रम से एपीआई कॉल करने के लिए सबसे सही है. इसमें अगला अनुरोध, पिछले अनुरोध के आउटपुट पर निर्भर करता है. इसलिए, यह एजेंटिक वर्कफ़्लो के लिए बैच से ज़्यादा फ़्लेक्सिबल होता है.

उपयोग के उदाहरण

  • ऑफ़लाइन आकलन: "एलएलएम-एज़-अ-जज" रिग्रेशन टेस्ट या लीडरबोर्ड चलाना.
  • बैकग्राउंड एजेंट: ऐसे टास्क जो क्रम से किए जाते हैं, जैसे कि सीआरएम अपडेट करना, प्रोफ़ाइल बनाना या कॉन्टेंट की निगरानी करना. इनमें कुछ मिनट की देरी स्वीकार की जा सकती है.
  • बजट की सीमा वाली रिसर्च: ऐसे शैक्षणिक एक्सपेरिमेंट जिनके लिए सीमित बजट में ज़्यादा टोकन की ज़रूरत होती है.

तय सीमाएं

फ़्लेक्स इन्फ़्रेंस के ट्रैफ़िक को, दर से जुड़ी सामान्य सीमाओं में गिना जाता है. इसमें Batch API की तरह, दर से जुड़ी ज़्यादा सीमाएं नहीं मिलती हैं.

शेड की जा सकने वाली क्षमता

फ़्लेक्स ट्रैफ़िक को कम प्राथमिकता दी जाती है. अगर स्टैंडर्ड ट्रैफ़िक में अचानक बढ़ोतरी होती है, तो ज़्यादा प्राथमिकता वाले उपयोगकर्ताओं के लिए क्षमता बनाए रखने के लिए, फ़्लेक्स अनुरोधों को रोका जा सकता है या उन्हें हटाया जा सकता है. अगर आपको प्राथमिकता के आधार पर अनुमान लगाने की सुविधा चाहिए, तो प्राथमिकता के आधार पर अनुमान लगाने की सुविधा देखें

गड़बड़ी के कोड

जब फ़्लेक्स क्षमता उपलब्ध नहीं होती है या सिस्टम पर ज़्यादा लोड होता है, तो एपीआई गड़बड़ी के स्टैंडर्ड कोड दिखाएगा:

  • 503 कोड वाली गड़बड़ी: सेवा उपलब्ध नहीं है: फ़िलहाल, सिस्टम पर काफ़ी ज़्यादा लोड है.
  • 429 कई बार अनुरोध किया गया: अनुरोधों की संख्या तय सीमा से ज़्यादा हो गई है या संसाधन खत्म हो गए हैं.

क्लाइंट की ज़िम्मेदारी

  • सर्वर साइड फ़ॉलबैक नहीं है: अचानक लगने वाले शुल्क से बचने के लिए, अगर Flex की क्षमता पूरी हो जाती है, तो सिस्टम Flex के अनुरोध को स्टैंडर्ड टियर में अपने-आप अपग्रेड नहीं करेगा.
  • फिर से कोशिश करना: आपको क्लाइंट-साइड पर, फिर से कोशिश करने का अपना लॉजिक लागू करना होगा. इसके लिए, एक्स्पोनेंशियल बैकऑफ़ का इस्तेमाल करें.
  • टाइमआउट: फ़्लेक्स अनुरोधों को एक कतार में रखा जा सकता है. इसलिए, हम क्लाइंट-साइड टाइमआउट को 10 मिनट या उससे ज़्यादा बढ़ाने का सुझाव देते हैं, ताकि कनेक्शन समय से पहले बंद न हो.

टाइम आउट विंडो में बदलाव करना

REST API और क्लाइंट लाइब्रेरी के लिए, हर अनुरोध के लिए टाइमआउट कॉन्फ़िगर किए जा सकते हैं. हालांकि, क्लाइंट लाइब्रेरी का इस्तेमाल करते समय ही ग्लोबल टाइमआउट कॉन्फ़िगर किए जा सकते हैं.

हमेशा पक्का करें कि क्लाइंट-साइड टाइमआउट, सर्वर के इंतज़ार करने की अवधि को कवर करता हो. उदाहरण के लिए, फ़्लेक्स की इंतज़ार कतारों के लिए 600 सेकंड से ज़्यादा. एसडीके, टाइम आउट की वैल्यू मिलीसेकंड में लेते हैं.

हर अनुरोध के लिए समयसीमाएं

Python

from google import genai

client = genai.Client()

try:
    response = client.models.generate_content(
        model="gemini-3-flash-preview",
        contents="why is the sky blue?",
        config={
            "service_tier": "flex",
            "http_options": {"timeout": 900000}
        },
    )
except Exception as e:
    print(f"Flex request failed: {e}")

# Example with streaming
try:
    response = client.models.generate_content_stream(
        model="gemini-3-flash-preview",
        contents=["List 5 ideas for a sci-fi movie."],
        config={
            "service_tier": "flex",
            "http_options": {"timeout": 60000}
        }
        # Per-request timeout for the streaming operation
    )
    for chunk in response:
        print(chunk.text, end="")

except Exception as e:
    print(f"An error occurred during streaming: {e}")

JavaScript

 import {GoogleGenAI} from '@google/genai';

 const client = new GoogleGenAI({});

 async function main() {
     try {
         const response = await client.models.generateContent({
             model: "gemini-3-flash-preview",
             contents: "why is the sky blue?",
             config: {
               serviceTier: "flex",
               httpOptions: {timeout: 900000}
             },
         });
     } catch (e) {
         console.log(`Flex request failed: ${e}`);
     }

     // Example with streaming
     try {
         const response = await client.models.generateContentStream({
             model: "gemini-3-flash-preview",
             contents: ["List 5 ideas for a sci-fi movie."],
             config: {
                 serviceTier: "flex",
                 httpOptions: {timeout: 60000}
             },
         });
         for await (const chunk of response.stream) {
             process.stdout.write(chunk.text());
         }
     } catch (e) {
         console.log(`An error occurred during streaming: ${e}`);
     }
 }

 await main();

ऐप पर जाएं

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "google.golang.org/api/iterator"
    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    timeoutCtx, cancel := context.WithTimeout(ctx, 900*time.Second)
    defer cancel()

    _, err = client.Models.GenerateContent(
        timeoutCtx,
        "gemini-3-flash-preview",
        genai.Text("why is the sky blue?"),
        &genai.GenerateContentConfig{
            ServiceTier: "flex",
        },
    )
    if err != nil {
        fmt.Printf("Flex request failed: %v\n", err)
    }

    // Example with streaming
    streamTimeoutCtx, streamCancel := context.WithTimeout(ctx, 60*time.Second)
    defer streamCancel()

    iter := client.Models.GenerateContentStream(
        streamTimeoutCtx,
        "gemini-3-flash-preview",
        genai.Text("List 5 ideas for a sci-fi movie."),
        &genai.GenerateContentConfig{
            ServiceTier: "flex",
        },
    )
    for {
        response, err := iter.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            fmt.Printf("An error occurred during streaming: %v\n", err)
            break
        }
        fmt.Print(response.Candidates[0].Content.Parts[0])
    }
}

REST

REST कॉल करते समय, एचटीटीपी हेडर और curl विकल्पों का इस्तेमाल करके टाइमआउट को कंट्रोल किया जा सकता है:

  • X-Server-Timeout हेडर (सर्वर-साइड टाइमआउट): यह हेडर, Gemini API सर्वर के लिए टाइमआउट की पसंदीदा अवधि (डिफ़ॉल्ट रूप से 600 सेकंड) का सुझाव देता है. सर्वर इस सेटिंग का पालन करने की कोशिश करेगा. हालांकि, इसकी कोई गारंटी नहीं है. वैल्यू सेकंड में होनी चाहिए.

  • --max-time में curl (क्लाइंट-साइड टाइमआउट): curl --max-time <seconds> विकल्प, कुल समय (सेकंड में) के लिए एक तय सीमा सेट करता है. curl इस सीमा तक पूरे ऑपरेशन के पूरा होने का इंतज़ार करेगा. यह क्लाइंट-साइड सेफ़गार्ड है.

 # Set a server timeout hint of 120 seconds and a client-side curl timeout of 125 seconds.
 curl --max-time 125 \
   -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
   -H "Content-Type: application/json" \
   -H "x-goog-api-key: YOUR_API_KEY" \
   -H "X-Server-Timeout: 120" \
   -d '{
   "contents": [{
     "parts":[{"text": "Summarize the latest research on quantum computing."}]
   }],
   "service_tier": "SERVICE_TIER_FLEX"
 }'

ग्लोबल टाइमआउट

अगर आपको किसी genai.Client इंस्टेंस (सिर्फ़ क्लाइंट लाइब्रेरी) के ज़रिए किए गए सभी एपीआई कॉल के लिए डिफ़ॉल्ट टाइम आउट सेट करना है, तो http_options और genai.types.HttpOptions का इस्तेमाल करके क्लाइंट को शुरू करते समय इसे कॉन्फ़िगर किया जा सकता है.

Python

from google import genai

global_timeout_ms = 120000

client_with_global_timeout = genai.Client(
    http_options=types.HttpOptions(timeout=global_timeout_ms)
)

try:
    # Calling generate_content using global timeout...
    response = client_with_global_timeout.models.generate_content(
        model="gemini-3-flash-preview",
        contents="Summarize the history of AI development since 2000.",
        config={"service_tier": "flex"},
    )
    print(response.text)

    # A per-request timeout will *override* the global timeout for that specific call.
    shorter_timeout = 30000
    response = client_with_global_timeout.models.generate_content(
        model="gemini-3-flash-preview",
        contents="Provide a very brief definition of machine learning.",
        config={
            "service_tier": "flex",
            "http_options":{"timeout": shorter_timeout}
        }  # Overrides the global timeout
    )

    print(response.text)

except TimeoutError:
    print(
        f"A GenerateContent call timed out. Check if the global or per-request timeout was exceeded."
    )
except Exception as e:
    print(f"An error occurred: {e}")

JavaScript

import {GoogleGenAI} from '@google/genai';

const globalTimeoutMs = 120000;

const clientWithGlobalTimeout = new GoogleGenAI({httpOptions: {timeout: globalTimeoutMs}});

async function main() {
    try {
        // Calling generate_content using global timeout...
        const response1 = await clientWithGlobalTimeout.models.generateContent({
            model: "gemini-3-flash-preview",
            contents: "Summarize the history of AI development since 2000.",
            config: { serviceTier: "flex" },
        });
        console.log(response1.text());

        // A per-request timeout will *override* the global timeout for that specific call.
        const shorterTimeout = 30000;
        const response2 = await clientWithGlobalTimeout.models.generateContent({
            model: "gemini-3-flash-preview",
            contents: "Provide a very brief definition of machine learning.",
            config: {
                serviceTier: "flex",
                httpOptions: {timeout: shorterTimeout}
            }  // Overrides the global timeout
        });

        console.log(response2.text());

    } catch (e) {
        if (e.name === 'TimeoutError' || e.message?.includes('timeout')) {
            console.log(
                "A GenerateContent call timed out. Check if the global or per-request timeout was exceeded."
            );
        } else {
            console.log(`An error occurred: ${e}`);
        }
    }
}

await main();

ऐप पर जाएं

 package main

 import (
     "context"
     "fmt"
     "log"
     "time"

     "google.golang.org/genai"
 )

 func main() {
     ctx := context.Background()
     client, err := genai.NewClient(ctx, nil)
     if err != nil {
         log.Fatal(err)
     }
     defer client.Close()

     model := client.GenerativeModel("gemini-3-flash-preview")

     // Go uses context for timeouts, not client options.
     // Set a default timeout for requests.
     globalTimeout := 120 * time.Second
     fmt.Printf("Using default timeout of %v seconds.\n", globalTimeout.Seconds())

     fmt.Println("Calling generate_content (using default timeout)...")
     ctx1, cancel1 := context.WithTimeout(ctx, globalTimeout)
     defer cancel1()
     resp1, err := model.GenerateContent(ctx1, genai.Text("Summarize the history of AI development since 2000."), &genai.GenerateContentConfig{ServiceTier: "flex"})
     if err != nil {
         log.Printf("Request 1 failed: %v", err)
     } else {
         fmt.Println("GenerateContent 1 successful.")
         fmt.Println(resp1.Text())
     }

     // A different timeout can be used for other requests.
     shorterTimeout := 30 * time.Second
     fmt.Printf("\nCalling generate_content with a shorter timeout of %v seconds...\n", shorterTimeout.Seconds())
     ctx2, cancel2 := context.WithTimeout(ctx, shorterTimeout)
     defer cancel2()
     resp2, err := model.GenerateContent(ctx2, genai.Text("Provide a very brief definition of machine learning."), &genai.GenerateContentConfig{
         ServiceTier: "flex",
     })
     if err != nil {
         log.Printf("Request 2 failed: %v", err)
     } else {
         fmt.Println("GenerateContent 2 successful.")
         fmt.Println(resp2.Text())
     }
 }

फिर से कोशिश करने की सुविधा लागू करना

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

Python

import time
from google import genai

client = genai.Client()

def call_with_retry(max_retries=3, base_delay=5):
    for attempt in range(max_retries):
        try:
            return client.models.generate_content(
                model="gemini-3-flash-preview",
                contents="Analyze this batch statement.",
                config={"service_tier": "flex"},
            )
        except Exception as e:
            # Check for 503 Service Unavailable or 429 Rate Limits
      print(e.code)
            if attempt < max_retries - 1:
                delay = base_delay * (2 ** attempt) # Exponential Backoff
                print(f"Flex busy, retrying in {delay}s...")
                time.sleep(delay)
            else:
                # Fallback to standard on last strike (Optional)
                print("Flex exhausted, falling back to Standard...")
                return client.models.generate_content(
                    model="gemini-3-flash-preview",
                    contents="Analyze this batch statement."
                )

# Usage
response = call_with_retry()
print(response.text)

JavaScript

 import {GoogleGenAI} from '@google/genai';

 const ai = new GoogleGenAI({});

 async function sleep(ms) {
   return new Promise(resolve => setTimeout(resolve, ms));
 }

 async function callWithRetry(maxRetries = 3, baseDelay = 5) {
   for (let attempt = 0; attempt < maxRetries; attempt++) {
     try {
       console.log(`Attempt ${attempt + 1}: Calling Flex tier...`);
       const response = await ai.models.generateContent({
         model: "gemini-3-flash-preview",
         contents: "Analyze this batch statement.",
         config: { serviceTier: 'flex' },
       });
       return response;
     } catch (e) {
       if (attempt < maxRetries - 1) {
         const delay = baseDelay * (2 ** attempt);
         console.log(`Flex busy, retrying in ${delay}s...`);
         await sleep(delay * 1000);
       } else {
         console.log("Flex exhausted, falling back to Standard...");
         return await ai.models.generateContent({
           model: "gemini-3-flash-preview",
           contents: "Analyze this batch statement.",
         });
       }
     }
   }
 }

 async function main() {
     const response = await callWithRetry();
     console.log(response.text);
 }

 await main();

ऐप पर जाएं

 package main

 import (
     "context"
     "fmt"
     "log"
     "math"
     "time"

     "google.golang.org/genai"
 )

 func callWithRetry(ctx context.Context, client *genai.Client, maxRetries int, baseDelay time.Duration) (*genai.GenerateContentResponse, error) {
     modelName := "gemini-3-flash-preview"
     content := genai.Text("Analyze this batch statement.")
     flexConfig := &genai.GenerateContentConfig{
         ServiceTier: "flex",
     }

     for attempt := 0; attempt < maxRetries; attempt++ {
         log.Printf("Attempt %d: Calling Flex tier...", attempt+1)
         resp, err := client.Models.GenerateContent(ctx, modelName, content, flexConfig)
         if err == nil {
             return resp, nil
         }

         log.Printf("Attempt %d failed: %v", attempt+1, err)

         if attempt < maxRetries-1 {
             delay := time.Duration(float64(baseDelay) * math.Pow(2, float64(attempt)))
             log.Printf("Flex busy, retrying in %v...", delay)
             time.Sleep(delay)
         } else {
             log.Println("Flex exhausted, falling back to Standard...")
             return client.Models.GenerateContent(ctx, modelName, content)
         }
     }
     return nil, fmt.Errorf("retries exhausted") // Should not be reached
 }

 func main() {
     ctx := context.Background()
     client, err := genai.NewClient(ctx, nil)
     if err != nil {
         log.Fatal(err)
     }
     defer client.Close()

     resp, err := callWithRetry(ctx, client, 3, 5*time.Second)
     if err != nil {
         log.Fatalf("Failed after retries: %v", err)
     }
     fmt.Println(resp.Text())
 }

कीमत

फ़्लेक्स इन्फ़रेंस की कीमत, स्टैंडर्ड एपीआई की कीमत का 50% होती है. इसका बिल हर टोकन के हिसाब से भेजा जाता है.

इन मॉडल के साथ काम करता है

इन मॉडल के साथ फ़्लेक्स इन्फ़रेंस की सुविधा काम करती है:

मॉडल Flex inference
Gemini 3.1 Flash-Lite की झलक ✔️
Gemini 3.1 Pro की झलक ✔️
Gemini 3 Flash की झलक ✔️
Gemini 3 Pro Image की झलक ✔️
Gemini 2.5 Pro ✔️
Gemini 2.5 Flash ✔️
Gemini 2.5 Flash की इमेज ✔️
Gemini 2.5 Flash-Lite ✔️

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

Gemini के अन्य अनुमान और ऑप्टिमाइज़ेशन विकल्पों के बारे में पढ़ें: