رابط برنامهنویسی Gemini Flex یک لایه استنتاج است که در مقایسه با نرخهای استاندارد، 50 درصد کاهش هزینه ارائه میدهد و در عوض، تأخیر متغیر و دسترسیپذیری با بهترین تلاش را ارائه میدهد. این رابط برای بارهای کاری مقاوم در برابر تأخیر طراحی شده است که نیاز به پردازش همزمان دارند اما به عملکرد بلادرنگ رابط برنامهنویسی استاندارد نیازی ندارند.
نحوه استفاده از فلکس
برای استفاده از لایه Flex، در بدنه درخواست، service_tier را به صورت flex مشخص کنید. به طور پیشفرض، اگر این فیلد حذف شود، درخواستها از لایه استاندارد استفاده میکنند.
پایتون
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}")
جاوا اسکریپت
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())
}
استراحت
"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 شکاف بین API استاندارد و گردش کار 24 ساعته Batch API را پر میکند. این سیستم از ظرفیت محاسباتی "قابل کاهش" و خارج از اوج مصرف استفاده میکند تا یک راهحل مقرونبهصرفه برای وظایف پسزمینه و گردشهای کاری متوالی ارائه دهد.
| ویژگی | فلکس | اولویت | استاندارد | دستهای |
|---|---|---|---|---|
| قیمتگذاری | ۵۰٪ تخفیف | ۷۵ تا ۱۰۰ درصد بیشتر از استاندارد | قیمت کامل | ۵۰٪ تخفیف |
| تأخیر | دقیقه (هدف ۱ تا ۱۵ دقیقه) | پایین (ثانیه) | ثانیه به دقیقه | تا ۲۴ ساعت |
| قابلیت اطمینان | بهترین تلاش (قابل کاهش) | زیاد (غیرقابل ریزش) | زیاد / متوسط-زیاد | بالا (برای توان عملیاتی) |
| رابط | همزمان | همزمان | همزمان | ناهمزمان |
مزایای کلیدی
- بهرهوری هزینه : صرفهجویی قابل توجه در ارزیابیهای غیرتولیدی، عوامل پسزمینه و غنیسازی دادهها.
- اصطکاک کم : نیازی به مدیریت اشیاء دستهای، شناسههای کار یا نظرسنجی نیست؛ به سادگی یک پارامتر واحد به درخواستهای موجود خود اضافه کنید.
- گردشهای کاری همزمان : برای زنجیرههای متوالی API که در آنها درخواست بعدی به خروجی درخواست قبلی بستگی دارد، ایدهآل است و آن را برای گردشهای کاری عاملی، انعطافپذیرتر از Batch میکند.
موارد استفاده
- ارزیابیهای آفلاین : اجرای آزمونهای رگرسیون یا جدول امتیازات «LLM به عنوان داور».
- عوامل پسزمینه : وظایف متوالی مانند بهروزرسانیهای CRM، ایجاد پروفایل یا مدیریت محتوا که در آنها دقایق تأخیر قابل قبول است.
- تحقیقات با بودجه محدود : آزمایشهای دانشگاهی که به حجم بالای توکن با بودجه محدود نیاز دارند.
محدودیتهای نرخ
ترافیک استنتاج Flex جزو محدودیتهای نرخ عمومی شما محسوب میشود؛ این سرویس مانند Batch API محدودیتهای نرخ توسعهیافته ارائه نمیدهد.
ظرفیت قابل تخلیه
ترافیک Flex با اولویت پایینتری مدیریت میشود. اگر افزایش ناگهانی در ترافیک استاندارد وجود داشته باشد، ممکن است درخواستهای Flex از دسترس خارج شوند یا حذف شوند تا ظرفیت برای کاربران با اولویت بالا تضمین شود. اگر به دنبال استنتاج با اولویت بالا هستید، استنتاج اولویت را بررسی کنید.
کدهای خطا
وقتی ظرفیت Flex در دسترس نباشد یا سیستم شلوغ باشد، API کدهای خطای استاندارد را برمیگرداند:
- ۵۰۳ سرویس در دسترس نیست : سیستم در حال حاضر ظرفیت کامل دارد.
- ۴۲۹ درخواستهای بیش از حد : محدودیتهای نرخ یا اتمام منابع.
مسئولیت مشتری
- بدون نیاز به پشتیبانگیری از سمت سرور : برای جلوگیری از هزینههای غیرمنتظره، سیستم در صورت پر بودن ظرفیت Flex، درخواست Flex را به طور خودکار به سطح استاندارد ارتقا نمیدهد.
- تلاشهای مجدد : شما باید منطق تلاش مجدد سمت کلاینت خود را با backoff نمایی پیادهسازی کنید.
- وقفهها : از آنجا که درخواستهای Flex ممکن است در صف انتظار بمانند، توصیه میکنیم وقفههای سمت کلاینت را به 10 دقیقه یا بیشتر افزایش دهید تا از بسته شدن زودهنگام اتصال جلوگیری شود.
تنظیم پنجرههای تایماوت
شما میتوانید برای REST API و کتابخانههای کلاینت، زمانهای انتظار به ازای هر درخواست و فقط هنگام استفاده از کتابخانههای کلاینت، زمانهای انتظار سراسری را پیکربندی کنید.
همیشه مطمئن شوید که timeout سمت کلاینت شما، بازه زمانی مورد نظر سرور برای صبر را پوشش میدهد (مثلاً، ۶۰۰+ ثانیه برای صفهای انتظار Flex). SDKها مقادیر timeout را بر حسب میلیثانیه قبول میکنند.
مهلتهای زمانی به ازای هر درخواست
پایتون
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}")
جاوا اسکریپت
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، میتوانید با استفاده از ترکیبی از هدرهای HTTP و گزینههای curl ، زمانهای انتظار را کنترل کنید:
هدر
X-Server-Timeout(زمان انتظار سمت سرور) : این هدر مدت زمان دلخواه برای زمان انتظار (پیشفرض ۶۰۰ ثانیه) را به سرور Gemini API پیشنهاد میدهد. سرور سعی میکند این را رعایت کند، اما تضمینی وجود ندارد. مقدار باید بر حسب ثانیه باشد.--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"
}'
وقفههای سراسری
اگر میخواهید تمام فراخوانیهای API که از طریق یک نمونه خاص genai.Client (فقط کتابخانههای کلاینت) انجام میشوند، یک timeout پیشفرض داشته باشند، میتوانید این را هنگام مقداردهی اولیه کلاینت با استفاده از http_options و genai.types.HttpOptions پیکربندی کنید.
پایتون
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}")
جاوا اسکریپت
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 از کار میافتد، در اینجا مثالی از پیادهسازی اختیاری منطق تلاش مجدد برای ادامه با درخواستهای ناموفق آورده شده است:
پایتون
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)
جاوا اسکریپت
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())
}
قیمتگذاری
استنتاج فلکس با قیمت ۵۰٪ از API استاندارد و به ازای هر توکن محاسبه میشود.
مدلهای پشتیبانیشده
مدلهای زیر از استنتاج Flex پشتیبانی میکنند:
| مدل | استنتاج انعطافپذیر |
|---|---|
| پیشنمایش Gemini 3.1 Flash-Lite | ✔️ |
| پیشنمایش Gemini 3.1 Pro | ✔️ |
| پیشنمایش فلش جمینی ۳ | ✔️ |
| پیشنمایش تصویر Gemini 3 Pro | ✔️ |
| جمینی ۲.۵ پرو | ✔️ |
| فلش جمینی ۲.۵ | ✔️ |
| تصویر فلش Gemini 2.5 | ✔️ |
| جمینی ۲.۵ فلش-لایت | ✔️ |
قدم بعدی چیست؟
درباره سایر گزینههای استنتاج و بهینهسازی Gemini بخوانید:
- استنتاج اولویت برای تأخیر بسیار کم.
- API دستهای برای پردازش ناهمزمان در عرض ۲۴ ساعت.
- ذخیرهسازی متن برای کاهش هزینههای توکن ورودی.