DEV Community

Cover image for Hướng Dẫn Sử Dụng Gemini 3.5 Flash API
Sebastian Petrus
Sebastian Petrus

Posted on • Originally published at apidog.com

Hướng Dẫn Sử Dụng Gemini 3.5 Flash API

API Gemini 3.5 Flash ra mắt cùng phiên bản mô hình vào ngày 19 tháng 5 năm 2026. Flash hiện là biến thể duy nhất của dòng 3.5; Pro sẽ ra mắt vào tháng 6. Bài viết này hướng dẫn cách thiết lập Flash từ đầu: lấy API key, gọi request đầu tiên, xử lý đầu vào đa phương thức, streaming, function calling, JSON output và kiểm thử tích hợp bằng Apidog.

Dùng thử Apidog ngay hôm nay

Nếu bạn đã dùng Gemini API trước đây, luồng tích hợp gần như không đổi. Điểm cần thay là tên mô hình: gemini-3.5-flash. Nếu bạn mới bắt đầu, bạn có thể chạy request Flash đầu tiên trong khoảng 10 phút.

Gemini 3.5 Flash API

Bạn nhận được gì với Gemini 3.5 Flash API

Ba điểm cần nắm trước khi triển khai:

  • Model name: gemini-3.5-flash
  • API pattern tương tự các phiên bản Gemini trước: dễ chuyển từ Gemini 3 hoặc Gemini 3.1
  • Có free tier trên Google AI Studio: khoảng 1.500 request/ngày, không cần thẻ tín dụng

Các khả năng chính của Flash:

  • Ngữ cảnh đầu vào 1 triệu token, đầu ra 64 nghìn token
  • Đầu vào văn bản + hình ảnh
  • Đầu ra văn bản hoặc có cấu trúc
  • Function calling và tool use gốc
  • Streaming response
  • Phù hợp cho truy xuất ngữ cảnh dài, phân tích tài liệu và biểu đồ

Để xem chi tiết chi phí theo token và batch mode, tham khảo hướng dẫn định giá Gemini 3.5 Flash.

Bước 1: Lấy API key cho Gemini 3.5 Flash

Bạn có hai lựa chọn: Google AI Studio cho thử nghiệm/free tier hoặc Vertex AI cho môi trường production.

Cách A: Google AI Studio

  1. Truy cập aistudio.google.com
  2. Đăng nhập bằng tài khoản Google
  3. Chọn Get API key ở thanh điều hướng bên trái
  4. Chọn project có sẵn hoặc tạo project mới
  5. Nhấn Create API key
  6. Sao chép API key và lưu vào biến môi trường

Ví dụ:

export GEMINI_API_KEY="your_api_key_here"
Enter fullscreen mode Exit fullscreen mode

Quy trình này giống với hướng dẫn lấy Gemini API key miễn phí. Key có thể dùng ngay với gemini-3.5-flash.

Google AI Studio API key

Cách B: Vertex AI cho production

Nếu bạn cần billing, IAM, audit log và quản trị theo tổ chức, dùng Vertex AI:

  1. Mở Google Cloud Console
  2. Bật Vertex AI API
  3. Tạo service account có quyền aiplatform.user
  4. Tải file credentials JSON
  5. Xác thực bằng một trong hai cách:
gcloud auth application-default login
Enter fullscreen mode Exit fullscreen mode

Hoặc đặt biến môi trường:

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
Enter fullscreen mode Exit fullscreen mode

Hầu hết team nên bắt đầu bằng AI Studio, sau đó chuyển sang Vertex AI khi cần kiểm soát production.

Bước 2: Cài đặt SDK

Google cung cấp GenAI SDK cho Python, Node.js, Go và Java.

# Python
pip install -U google-genai

# Node.js
npm install @google/genai

# Go
go get google.golang.org/genai
Enter fullscreen mode Exit fullscreen mode

Nếu không muốn dùng SDK, bạn có thể gọi trực tiếp REST API bằng curl.

Bước 3: Gọi request Flash đầu tiên

Python

import os
from google import genai

client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="Explain how OAuth 2.0 PKCE flow works in 3 short paragraphs."
)

print(response.text)
Enter fullscreen mode Exit fullscreen mode

Node.js

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

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const response = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: "Explain how OAuth 2.0 PKCE flow works in 3 short paragraphs.",
});

console.log(response.text);
Enter fullscreen mode Exit fullscreen mode

curl

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{
      "parts": [{"text": "Explain how OAuth 2.0 PKCE flow works in 3 short paragraphs."}]
    }]
  }'
Enter fullscreen mode Exit fullscreen mode

Đến đây, bạn đã có request Gemini 3.5 Flash cơ bản. Các phần tiếp theo là những tính năng thường cần khi đưa vào ứng dụng thật.

Streaming response

Streaming giúp UI phản hồi nhanh hơn vì người dùng thấy token xuất hiện dần thay vì chờ toàn bộ kết quả.

Python

stream = client.models.generate_content_stream(
    model="gemini-3.5-flash",
    contents="Write a 5-step tutorial on writing a REST API client in Go."
)

for chunk in stream:
    print(chunk.text, end="", flush=True)
Enter fullscreen mode Exit fullscreen mode

Node.js

const stream = await ai.models.generateContentStream({
  model: "gemini-3.5-flash",
  contents: "Write a 5-step tutorial on writing a REST API client in Go.",
});

for await (const chunk of stream) {
  process.stdout.write(chunk.text);
}
Enter fullscreen mode Exit fullscreen mode

Với REST API, đổi endpoint từ:

:generateContent
Enter fullscreen mode Exit fullscreen mode

thành:

:streamGenerateContent
Enter fullscreen mode Exit fullscreen mode

Đầu vào đa phương thức với Flash

Gemini 3.5 Flash hỗ trợ đầu vào hình ảnh cùng với văn bản. Mẫu phổ biến là trích xuất thông tin từ dashboard, biểu đồ, ảnh chụp màn hình hoặc tài liệu scan.

Python: gửi ảnh từ ổ đĩa

import os
from google import genai
from google.genai import types

client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

with open("dashboard.png", "rb") as f:
    image_bytes = f.read()

response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=[
        types.Part.from_bytes(data=image_bytes, mime_type="image/png"),
        "Extract every metric in this dashboard as a JSON object."
    ]
)

print(response.text)
Enter fullscreen mode Exit fullscreen mode

Các MIME type hình ảnh được hỗ trợ:

  • image/png
  • image/jpeg
  • image/webp
  • image/heic
  • image/heif

PDF và video cũng có thể xử lý qua types.Part.from_uri().

Function calling và tool use

Function calling cho phép model chọn tool phù hợp, trả về tên hàm và arguments để ứng dụng của bạn thực thi.

Python

from google.genai import types

weather_tool = types.Tool(
    function_declarations=[{
        "name": "get_current_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["city"]
        }
    }]
)

response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="What's the weather in Singapore right now?",
    config=types.GenerateContentConfig(tools=[weather_tool])
)

for part in response.candidates[0].content.parts:
    if part.function_call:
        print(f"Call: {part.function_call.name}")
        print(f"Args: {dict(part.function_call.args)}")
Enter fullscreen mode Exit fullscreen mode

Luồng xử lý thường là:

  1. Gửi prompt + tool schema cho Flash
  2. Nhận function_call
  3. Thực thi hàm trong backend của bạn
  4. Gửi kết quả hàm lại cho model
  5. Nhận câu trả lời cuối cùng

Mẫu này tương tự cách các team đã dùng với Gemini 3 Flash API.

Đầu ra có cấu trúc bằng JSON mode

Nếu bạn cần output ổn định cho backend, hãy ép Flash trả về JSON bằng response_mime_typeresponse_schema.

import json
from google.genai import types

response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="List 3 popular API testing tools with their pricing.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json",
        response_schema={
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "price_per_month": {"type": "number"},
                    "free_tier": {"type": "boolean"}
                },
                "required": ["name", "free_tier"]
            }
        }
    )
)

data = json.loads(response.text)
print(data)
Enter fullscreen mode Exit fullscreen mode

Cách này giúp giảm nhu cầu parse bằng regex hoặc viết retry loop chỉ để sửa JSON sai định dạng.

Giá cả tính đến tháng 5 năm 2026

Mức giá pay-as-you-go cho gemini-3.5-flash:

Cấp độ Đầu vào Đầu ra
Tiêu chuẩn ~$1.50 / 1 triệu token ~$9.00 / 1 triệu token
Đầu vào được lưu vào bộ nhớ cache giá giảm không áp dụng
Chế độ hàng loạt giảm ~50% giảm ~50%

Với workload không yêu cầu độ trễ thời gian thực, batch mode của Gemini API có thể giảm khoảng 50% chi phí.

Để xem phân tích chi phí theo workload SaaS, agent loop và token usage thực tế, đọc thêm phân tích giá Gemini 3.5 Flash. Tài liệu chính thức của Google nằm tại Gemini Developer API pricing.

Kiểm thử tích hợp Gemini 3.5 Flash bằng Apidog

Một request SDK chạy được chưa đủ cho production. Bạn vẫn cần kiểm thử:

  • Streaming chunks
  • Function calling schema
  • Payload đa phương thức
  • Retry khi lỗi
  • Rate limit
  • JSON output validation

Kiểm thử Gemini API bằng Apidog

Apidog giúp bạn kiểm thử toàn bộ API surface của Gemini Flash trong một workspace:

  • Lưu endpoint Flash thành request: dán URL, thêm header x-goog-api-key, nhấn Send
  • So sánh nhiều model: đổi gemini-3.5-flash sang gemini-3-flash trong cùng request để so sánh output
  • Debug streaming response: xem từng chunk khi được trả về
  • Validate JSON schema: thêm assertion để phát hiện output lệch schema
  • Mock endpoint: tạo response giả để test downstream code mà không tốn quota
  • Test agent loop: xâu chuỗi nhiều request và kiểm tra function call giữa các bước

Cách bắt đầu nhanh:

  1. Tải Apidog
  2. Tạo request mới
  3. Dán endpoint Flash:
https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent
Enter fullscreen mode Exit fullscreen mode
  1. Thêm header:
x-goog-api-key: {{GEMINI_API_KEY}}
Content-Type: application/json
Enter fullscreen mode Exit fullscreen mode
  1. Dán body từ ví dụ curl
  2. Gửi request và lưu lại làm test case

Xử lý lỗi và rate limit

Các mã lỗi thường gặp:

  • 400: request không hợp lệ, thường do contents sai format hoặc MIME type không hỗ trợ
  • 401: API key không hợp lệ
  • 403: hết quota hoặc model chưa được bật
  • 429: bị rate limit
  • 500/503: lỗi server, nên retry với exponential backoff

Ví dụ retry đơn giản trong Python:

import time
from google import genai

def call_with_retry(client, model, prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.models.generate_content(
                model=model,
                contents=prompt
            )
        except Exception:
            if attempt == max_retries - 1:
                raise

            sleep_seconds = 2 ** attempt
            time.sleep(sleep_seconds)
Enter fullscreen mode Exit fullscreen mode

Free tier được reset hằng ngày, khoảng 15 request/phút và khoảng 1.500 request/ngày cho Flash. Production quota thường được kiểm soát theo phút và theo ngày.

Nếu workload cần thông lượng cao, hãy cân nhắc:

  • Batch mode cho tác vụ không realtime
  • Retry queue
  • Circuit breaker
  • Fallback sang Gemini 3 Flash khi chạm giới hạn

Di chuyển từ Gemini 3.1 sang 3.5 Flash

Trong nhiều dự án, thay đổi chính chỉ là model name.

# Trước đây
model = "gemini-3.1-pro"  # hoặc gemini-3.1-flash

# Sau khi chuyển
model = "gemini-3.5-flash"
Enter fullscreen mode Exit fullscreen mode

Sau khi đổi model, nên kiểm tra lại:

  1. Tool schema: đảm bảo arguments vẫn đúng với schema bạn định nghĩa
  2. Streaming UI: Flash có thể trả output nhanh hơn, UI có thể cần throttle
  3. Token budget: giới hạn vẫn là 1M input / 64K output, nhưng output thực tế có thể khác
  4. Safety behavior: các phản hồi từ chối có thể khác ở edge cases
  5. JSON schema validation: chạy lại test để tránh breaking change trong backend

Tham khảo thêm hướng dẫn Gemini 3.1 Pro API nếu bạn đang migrate từ SDK pattern cũ.

Các mẫu triển khai phổ biến

1. Phân tích tài liệu ngữ cảnh dài

from google.genai import types

with open("large_report.pdf", "rb") as f:
    pdf_bytes = f.read()

response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=[
        types.Part.from_bytes(
            data=pdf_bytes,
            mime_type="application/pdf"
        ),
        "Summarize the financial outlook from this report in 5 bullet points."
    ]
)

print(response.text)
Enter fullscreen mode Exit fullscreen mode

Ngữ cảnh 1 triệu token giúp xử lý tài liệu lớn mà không cần chia nhỏ thủ công trong nhiều trường hợp.

2. Trích xuất dữ liệu từ biểu đồ sang JSON

response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=[
        types.Part.from_bytes(
            data=open("chart.png", "rb").read(),
            mime_type="image/png"
        ),
        "Return the chart data as JSON with labels, values, and units."
    ],
    config=types.GenerateContentConfig(
        response_mime_type="application/json"
    )
)

chart_data = json.loads(response.text)
Enter fullscreen mode Exit fullscreen mode

Mẫu này hữu ích cho dashboard screenshot, báo cáo vận hành hoặc tài liệu phân tích.

3. Agent loop với function calling

conversation = [
    {
        "role": "user",
        "parts": [{"text": "Book me a flight to Tokyo"}]
    }
]

while True:
    response = client.models.generate_content(
        model="gemini-3.5-flash",
        contents=conversation,
        config=types.GenerateContentConfig(
            tools=[flight_search_tool, booking_tool]
        )
    )

    part = response.candidates[0].content.parts[0]

    if not part.function_call:
        print(part.text)
        break

    result = execute_tool(part.function_call)

    conversation.append({
        "role": "model",
        "parts": [part]
    })

    conversation.append({
        "role": "user",
        "parts": [{"function_response": result}]
    })
Enter fullscreen mode Exit fullscreen mode

Đây là pattern cơ bản để xây dựng agent có khả năng gọi API nội bộ, tra cứu dữ liệu và thực hiện hành động.

Câu hỏi thường gặp

Có free tier cho Gemini 3.5 Flash API không?

Có. Bạn có thể dùng thông qua Google AI Studio với quota hằng ngày khoảng 1.500 request/ngày. Không cần thẻ tín dụng.

Flash có hỗ trợ endpoint tương thích OpenAI không?

Có. Google cung cấp shim tương thích OpenAI tại:

/v1beta/openai/
Enter fullscreen mode Exit fullscreen mode

Bạn có thể trỏ OpenAI SDK đến endpoint này bằng base_url và dùng Gemini API key. Model name vẫn là:

gemini-3.5-flash
Enter fullscreen mode Exit fullscreen mode

Có dùng Flash với LangChain hoặc LlamaIndex được không?

Có. Cả hai đều có tích hợp Gemini. Truyền model name tương ứng:

model="gemini-3.5-flash"
Enter fullscreen mode Exit fullscreen mode

Khi nào Gemini 3.5 Pro ra mắt?

Theo thông báo ra mắt của Google, Gemini 3.5 Pro dự kiến ra mắt vào tháng 6 năm 2026. Trước thời điểm đó, Flash là biến thể 3.5 duy nhất có sẵn.

Kích thước hình ảnh tối đa nên dùng là bao nhiêu?

Khuyến nghị 3072×3072. Ảnh lớn hơn có thể được lấy mẫu lại. Nếu workload tập trung vào OCR, bạn có thể tham khảo thêm quy trình OCR với Gemini 2.0 Flash; pattern triển khai tương tự vẫn áp dụng.

Làm thế nào để test streaming endpoint trong Apidog?

Tạo request với hậu tố endpoint:

:streamGenerateContent
Enter fullscreen mode Exit fullscreen mode

Apidog sẽ hiển thị các SSE chunk khi chúng đến, giúp debug response bị thiếu hoặc bị ngắt giữa chừng.

Xem API log ở đâu?

  • AI Studio: mục Activity
  • Vertex AI: Logs Explorer trong Google Cloud Console

Nên xây dựng gì đầu tiên?

Nếu bạn muốn thử Gemini 3.5 Flash trong tuần đầu tiên, bắt đầu với một trong các project nhỏ sau:

  • PDF Q&A bot: đưa PDF vào context 1 triệu token, hỏi đáp và trả về câu trả lời có trích dẫn
  • Chart-to-JSON pipeline: gửi ảnh dashboard, trích xuất dữ liệu có cấu trúc
  • Customer support agent: dùng function calling để đọc CRM hoặc ticket system
  • Code review assistant: phân tích nhiều file, trả output JSON với severity
  • Internal search agent: kết hợp long context với tool call đến API nội bộ

Quy trình triển khai nên giữ đơn giản:

  1. Viết prompt nhỏ và rõ
  2. Gọi gemini-3.5-flash bằng SDK hoặc REST
  3. Ép output JSON nếu backend cần dữ liệu có cấu trúc
  4. Thêm retry/backoff cho lỗi 429 và 5xx
  5. Kiểm thử request, streaming và schema bằng Apidog
  6. Đưa vào production sau khi đã có test case ổn định

Top comments (0)