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 là độ trễ biến thiên và khả năng đáp ứng 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ó khả năng chịu độ trễ, 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 Linh hoạt, hãy chỉ định service_tier là flex trong yêu cầu của bạn. 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
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Analyze this dataset for trends...",
service_tier='flex'
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
async function main() {
const interaction = await client.interactions.create({
model: 'gemini-3.8-flash',
input: 'Analyze this dataset for trends...',
service_tier: 'flex'
});
console.log(interaction.output_text);
}
await main();
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ServiceTier;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Analyze this dataset for trends..."))
.serviceTier(ServiceTier.FLEX)
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Go
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("Analyze this dataset for trends..."),
ServiceTier: interactions.ServiceTierFlex.ToPointer(),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3.8-flash",
"input": "Analyze this dataset for trends...",
"service_tier": "flex"
}'
Cách hoạt động của suy luận Flex
Mô hình suy luận Gemini Flex 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. Dịch vụ này sử dụng công suất điện toán "có thể giảm tải" ngoài giờ cao điểm để cung cấp giải pháp tiết kiệm chi phí cho các tác vụ trong nền và quy trình công việc tuần tự.
| Tính năng | Gập | Mức độ ưu tiên | Chuẩn | Theo nhóm |
|---|---|---|---|---|
| Định giá | Giảm giá 50% | Cao hơn 75 – 100% so với gói Standard | Giá đầy đủ | Giảm giá 50% |
| Độ trễ | Phút (mục tiêu từ 1 đến 15 phút) | Thấp (giây) | Giây sang phút | Tối đa 24 giờ |
| Độ tin cậy | Nỗ lực tối đa (Có thể loại bỏ) | Cao (Không thể giảm tải) | Cao / Cao vừa | 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
- Hiệu quả về 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 nền và hoạt động làm phong phú dữ liệu.
- Ít rắc rối: Bạ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 đồng bộ: Phù hợp với các chuỗi API tuần tự, trong đó yêu cầu tiếp theo phụ thuộc vào kết quả của yêu cầu trước đó, giúp quy trình này linh hoạt hơn so với Batch cho quy trình 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 nền: Các nhiệm vụ tuần tự như cập nhật CRM, xây dựng hồ sơ hoặc người kiểm duyệt nội dung, trong đó có thể chấp nhận độ trễ vài 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 lớn trong 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 của tính năng suy luận Flex được tính vào giới hạn tốc độ chung; tính năng này không cung cấp giới hạn tốc độ mở rộng như Batch API.
Công suất có thể giảm
Lưu lượng truy cập linh hoạt đượ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 Suy luận ưu tiên
Mã lỗi
Khi không có dung lượng linh hoạt 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 đang hoạt động hết công suất.
- 429 Too Many Requests (429: Quá nhiều yêu cầu): Giới hạn về tốc độ hoặc cạn kiệt tài nguyên.
Trách nhiệm của khách hàng
- Không có phương án dự phòng phía máy chủ: Để tránh các khoản phí ngoài dự kiến, hệ thống sẽ không tự động nâng cấp yêu cầu Flex lên cấp Standard 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 việc đó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. Luôn đảm bảo thời gian chờ phía máy khách bao gồm cả khoảng thời gian chờ dự kiến của máy chủ (ví dụ: hơn 600 giây cho hàng đợi chờ Flex). Các SDK dự kiến 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(http_options={"timeout": 900000})
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="why is the sky blue?",
service_tier="flex",
)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
async function main() {
const interaction = await client.interactions.create({
model: "gemini-3.8-flash",
input: "why is the sky blue?",
service_tier: "flex",
}, {timeout: 900000});
}
await main();
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ServiceTier;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.HttpOptions;
Client client =
Client.builder()
.httpOptions(HttpOptions.builder().timeout(900000).build())
.build();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("why is the sky blue?"))
.serviceTier(ServiceTier.FLEX)
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
Go
package main
import (
"context"
"log"
"time"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{
Timeout: genai.Ptr(15 * time.Minute),
},
})
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("why is the sky blue?"),
ServiceTier: interactions.ServiceTierFlex.ToPointer(),
}),
})
if err != nil {
log.Fatal(err)
}
_ = res
}
Triển khai cơ chế thử lại
Vì Flex có thể bị loại bỏ và không thành công với lỗi 503, nên dưới đây là ví dụ về việc 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.interactions.create(
model="gemini-3.8-flash",
input="Analyze this batch statement.",
service_tier="flex",
)
except Exception as e:
if attempt < max_retries - 1:
delay = base_delay * (2 ** attempt) # Exponential Backoff
print(f"Flex busy, retrying in {delay}s...")
time.sleep(delay)
else:
print("Flex exhausted, falling back to Standard...")
return client.interactions.create(
model="gemini-3.8-flash",
input="Analyze this batch statement."
)
interaction = call_with_retry()
print(interaction.output_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 interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Analyze this batch statement.",
service_tier: 'flex',
});
return interaction;
} 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.interactions.create({
model: "gemini-3.8-flash",
input: "Analyze this batch statement.",
});
}
}
}
}
async function main() {
const interaction = await callWithRetry();
console.log(interaction.output_text);
}
await main();
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ServiceTier;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
int maxRetries = 3;
int baseDelay = 5;
Interaction interaction = null;
for (int attempt = 0; attempt < maxRetries; attempt++) {
try {
CreateModelInteraction flexParams =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Analyze this batch statement."))
.serviceTier(ServiceTier.FLEX)
.build();
interaction =
client.interactions.create(CreateInteractionRequestBody.of(flexParams)).interaction().get();
break;
} catch (Exception e) {
if (attempt < maxRetries - 1) {
int delay = baseDelay * (1 << attempt); // Exponential Backoff
System.out.println("Flex busy, retrying in " + delay + "s...");
Thread.sleep(delay * 1000L);
} else {
System.out.println("Flex exhausted, falling back to Standard...");
CreateModelInteraction standardParams =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Analyze this batch statement."))
.build();
interaction =
client
.interactions
.create(CreateInteractionRequestBody.of(standardParams))
.interaction()
.get();
}
}
}
if (interaction != null) {
System.out.println(interaction.outputText().orElse(""));
}
Go
package main
import (
"context"
"fmt"
"log"
"time"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
maxRetries := 3
baseDelay := 5
var interaction *interactions.Interaction
for attempt := 0; attempt < maxRetries; attempt++ {
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("Analyze this batch statement."),
ServiceTier: interactions.ServiceTierFlex.ToPointer(),
}),
})
if err == nil {
interaction = res.Interaction
break
}
if attempt < maxRetries-1 {
delay := baseDelay * (1 << attempt) // Exponential Backoff
fmt.Printf("Flex busy, retrying in %ds...\n", delay)
time.Sleep(time.Duration(delay) * time.Second)
} else {
fmt.Println("Flex exhausted, falling back to Standard...")
stdRes, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("Analyze this batch statement."),
}),
})
if err != nil {
log.Fatal(err)
}
interaction = stdRes.Interaction
}
}
if interaction != nil && interaction.OutputText != nil {
fmt.Println(*interaction.OutputText)
}
}
Giá
Suy luận Flex có giá bằng 50% so với API tiêu chuẩn và được tính phí theo token.
Mô hình được hỗ trợ
Các mô hình sau hỗ trợ tính năng suy luận Flex:
| Mô hình | Suy luận linh hoạt |
|---|---|
| Gemini 4 Argon | ✔️ |
| Gemini 3.8 Flash | ✔️ |
| Gemini 3.6 Flash | ✔️ |
| Gemini 3.5 Flash-Lite | ✔️ |
| Gemini 3.1 Flash-Lite | ✔️ |
| Bản dùng thử Gemini 3.1 Pro | ✔️ |
| Gemini 3 Flash Preview | ✔️ |
| Gemini 2.5 Pro | ✔️ |
| Gemini 2.5 Flash | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ |
Bước tiếp theo
- Suy luận ưu tiên để có độ trễ cực thấp.
- Mã thông báo: Tìm hiểu về mã thông báo.