Gemini Flex API là một cấp suy luận giúp giảm 50% chi phí so với mức giá tiêu chuẩn, đổi lại độ trễ có thể thay đổi và khả năng cung cấp tốt nhất có thể. API này được thiết kế cho các khối lượng công việc có độ trễ cao, yêu cầu xử lý đồng bộ nhưng không cần hiệu suất theo thời gian thực của API tiêu chuẩn.
Cách sử dụng Flex
Để sử dụng cấp Flex, hãy chỉ định service_tier là flex trong nội dung yêu cầu. Theo mặc định, các yêu cầu sẽ sử dụng cấp tiêu chuẩn nếu bạn bỏ qua trường này.
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();
Go
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"
}'
Cách hoạt động của suy luận Flex
Suy luận Gemini Flex giúp thu hẹp khoảng cách giữa API tiêu chuẩn và thời gian xử lý 24 giờ của Batch API. API này tận dụng khả năng tính toán "có thể loại bỏ" ngoài giờ cao điểm để cung cấp một giải pháp tiết kiệm chi phí cho các tác vụ trong nền và quy trình làm việc tuần tự.
| Tính năng | Gập | Mức độ ưu tiên | Tiêu chuẩn | Theo nhóm |
|---|---|---|---|---|
| Định giá | Giảm 50% | Cao hơn 75 – 100% so với Tiêu chuẩn | Giá đầy đủ | Giảm 50% |
| Độ trễ | Phút (mục tiêu 1–15 phút) | Thấp (Giây) | Giây đến phút | Tối đa 24 giờ |
| Độ tin cậy | Trong khả năng tốt nhất có thể (Có thể loại bỏ) | Cao (Không thể loại bỏ) | Cao / Trung bình cao | Cao (đối với thông lượng) |
| Giao diện | Đồng bộ | Đồng bộ | Đồng bộ | Không đồng bộ |
Lợi ích chính
- Tiết kiệm chi phí: Tiết kiệm đáng kể cho các hoạt động đánh giá không phải sản xuất, tác nhân trong nền và làm phong phú dữ liệu.
- Ít gây trở ngại: Không cần quản lý các đối tượng theo nhóm, mã công việc hoặc thăm dò ý kiến; chỉ cần thêm một tham số duy nhất vào các yêu cầu hiện có.
- Quy trình làm việc đồng bộ: Lý tưởng cho các chuỗi API tuần tự, trong đó yêu cầu tiếp theo phụ thuộc vào đầu ra của yêu cầu trước đó, giúp quy trình này linh hoạt hơn so với Batch đối với các quy trình làm việc của tác nhân.
Trường hợp sử dụng
- Đánh giá ngoại tuyến: Chạy các bài kiểm thử hồi quy "LLM-as-a-judge" hoặc bảng xếp hạng.
- Tác nhân trong nền: Các tác vụ tuần tự như cập nhật CRM, xây dựng hồ sơ hoặc kiểm duyệt nội dung, trong đó có thể chấp nhận độ trễ tính bằng phút.
- Nghiên cứu ràng buộc ngân sách: Các thử nghiệm học thuật yêu cầu số lượng token cao với ngân sách hạn chế.
Giới hạn số lượng yêu cầu
Lưu lượng truy cập suy luận Flex được tính vào giới hạn số lượng yêu cầu chung; lưu lượng truy cập này không cung cấp giới hạn số lượng yêu cầu mở rộng như Batch API.
Dung lượng có thể loại bỏ
Lưu lượng truy cập Flex được xử lý với mức độ ưu tiên thấp hơn. Nếu lưu lượng truy cập tiêu chuẩn tăng đột biến, các yêu cầu Flex có thể bị ưu tiên hoặc bị loại bỏ để đảm bảo dung lượng cho người dùng có mức độ ưu tiên cao. Nếu bạn đang tìm kiếm suy luận có mức độ ưu tiên cao, hãy xem phần Suy luận ưu tiên
Mã lỗi
Khi dung lượng Flex không có sẵn hoặc hệ thống bị tắc nghẽn, API sẽ trả về mã lỗi tiêu chuẩn:
- 503 Không có dịch vụ: Hệ thống hiện đang ở mức dung lượng tối đa.
- 429 Quá nhiều yêu cầu: Giới hạn số lượng yêu cầu hoặc cạn kiệt tài nguyên.
Trách nhiệm của ứng dụng
- Không có phương án dự phòng phía máy chủ: Để ngăn các khoản phí không mong muốn, hệ thống sẽ không tự động nâng cấp yêu cầu Flex lên cấp Tiêu chuẩn nếu dung lượng Flex đã đầy.
- Thử lại: Bạn phải triển khai logic thử lại phía máy khách của riêng mình bằng thuật toán đợi luỹ tuyến.
- Thời gian chờ: Vì các yêu cầu Flex có thể nằm trong hàng đợi, nên bạn nên tăng thời gian chờ phía máy khách lên 10 phút trở lên để tránh đóng kết nối sớm.
Điều chỉnh khoảng thời gian chờ
Bạn có thể định cấu hình thời gian chờ cho mỗi yêu cầu đối với API REST và thư viện ứng dụng, đồng thời chỉ định cấu hình thời gian chờ chung khi sử dụng thư viện ứng dụng.
Luôn đảm bảo thời gian chờ phía máy khách bao gồm khoảng thời gian chờ dự kiến của máy chủ (ví dụ: 600 giây trở lên đối với hàng đợi chờ Flex). SDK mong đợi các giá trị thời gian chờ tính bằng mili giây.
Thời gian chờ cho mỗi yêu cầu
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();
Go
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
Khi thực hiện các lệnh gọi REST, bạn có thể kiểm soát thời gian chờ bằng cách kết hợp các tiêu đề HTTP và tuỳ chọn curl:
Tiêu đề
X-Server-Timeout(thời gian chờ phía máy chủ): Tiêu đề này đề xuất thời lượng thời gian chờ ưu tiên (mặc định là 600 giây) cho máy chủ Gemini API. Máy chủ sẽ cố gắng tuân thủ thời lượng này, nhưng không đảm bảo. Giá trị phải tính bằng giây.--max-timetrongcurl(Thời gian chờ phía ứng dụng): Tuỳ chọncurl --max-time <seconds>đặt giới hạn cứng cho tổng thời gian (tính bằng giây) màcurlsẽ chờ để hoàn tất toàn bộ thao tác. Đây là biện pháp bảo vệ phía máy khách.
# 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"
}'
Thời gian chờ chung
Nếu bạn muốn tất cả các lệnh gọi API được thực hiện thông qua một thực thể genai.Client cụ thể (chỉ thư viện ứng dụng) có thời gian chờ mặc định, bạn có thể định cấu hình thời gian chờ này khi khởi chạy ứng dụng bằng cách sử dụng http_options và 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();
Go
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())
}
}
Triển khai tính năng thử lại
Vì Flex có thể loại bỏ và không thành công với lỗi 503, nên sau đây là ví dụ về cách triển khai logic thử lại (không bắt buộc) để tiếp tục với các yêu cầu không thành công:
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();
Go
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())
}
Định giá
Suy luận Flex được định giá bằng 50% API tiêu chuẩn và được tính phí theo mỗi mã thông báo.
Mô hình được hỗ trợ
Các mô hình sau đây hỗ trợ suy luận Flex:
| Mô hình | Suy luận Flex |
|---|---|
| Bản xem trước Gemini 3.1 Flash-Lite | ✔️ |
| Bản xem trước Gemini 3.1 Pro | ✔️ |
| Bản xem trước Gemini 3 Flash | ✔️ |
| Bản xem trước hình ảnh Gemini 3 Pro | ✔️ |
| Gemini 2.5 Pro | ✔️ |
| Gemini 2.5 Flash | ✔️ |
| Hình ảnh Gemini 2.5 Flash | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ |
Bước tiếp theo
Đọc thông tin về các lựa chọn suy luận và tối ưu hoá khác của Gemini:
- Suy luận ưu tiên để có độ trễ thấp nhất.
- Batch API để xử lý không đồng bộ trong vòng 24 giờ.
- Bộ nhớ đệm ngữ cảnh để giảm chi phí mã thông báo đầu vào.