Gemini và các mô hình AI tạo sinh khác xử lý dữ liệu đầu vào và đầu ra ở mức độ chi tiết được gọi là mã thông báo.
Đối với các mô hình Gemini, một mã thông báo tương đương với khoảng 4 ký tự. 100 mã tương đương với khoảng 60-80 từ tiếng Anh.
Giới thiệu về mã thông báo
Mã thông báo có thể là các ký tự đơn lẻ như z hoặc toàn bộ từ như cat. Các từ dài được chia thành nhiều mã thông báo. Tập hợp tất cả mã thông báo mà mô hình sử dụng được gọi là từ vựng và quá trình phân tách văn bản thành mã thông báo được gọi là mã hoá.
Khi bạn bật tính năng thanh toán, chi phí của một lệnh gọi đến Gemini API sẽ được xác định một phần dựa trên số lượng token đầu vào và đầu ra. Do đó, bạn nên biết cách đếm token.
Đếm số token
Tất cả dữ liệu đầu vào và đầu ra của Gemini API đều được mã hoá, bao gồm cả văn bản, tệp hình ảnh và các phương thức không phải văn bản khác.
Bạn có thể đếm mã thông báo theo những cách sau:
Gọi
count_tokensvới dữ liệu đầu vào của yêu cầu. Trả về tổng số mã thông báo trong chỉ dữ liệu đầu vào. Thực hiện lệnh gọi này trước khi gửi dữ liệu đầu vào để kiểm tra kích thước của yêu cầu.Sử dụng
usagetrên phản hồi tương tác. Trả về số lượng mã thông báo cho dữ liệu đầu vào (total_input_tokens), dữ liệu đầu ra (total_output_tokens), suy nghĩ (total_thought_tokens), nội dung được lưu vào bộ nhớ đệm (total_cached_tokens), việc sử dụng công cụ (total_tool_use_tokens) và tổng số (total_tokens).
Đếm số token văn bản
Python
# This will only work for SDK newer than 2.0.0
from google import genai
client = genai.Client()
prompt = "The quick brown fox jumps over the lazy dog."
# Count tokens before sending
total_tokens = client.models.count_tokens(
model="gemini-3.8-flash",
contents=prompt
)
print("total_tokens:", total_tokens.total_tokens)
# Get usage from interaction
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=prompt
)
print(interaction.usage)
JavaScript
// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const prompt = "The quick brown fox jumps over the lazy dog.";
// Count tokens before sending
const countResponse = await client.models.countTokens({
model: "gemini-3.8-flash",
contents: prompt,
});
console.log(countResponse.totalTokens);
// Get usage from interaction
const interaction = await client.interactions.create({
model: "gemini-3.8-flash",
input: prompt,
});
console.log(interaction.usage);
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.operations.CreateInteractionRequestBody;
import com.google.genai.types.CountTokensResponse;
Client client = new Client();
String prompt = "The quick brown fox jumps over the lazy dog.";
// Count tokens before sending
CountTokensResponse countResponse =
client.models.countTokens("gemini-3.8-flash", prompt, null);
System.out.println("total_tokens: " + countResponse.totalTokens().orElse(0));
// Get usage from interaction
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of(prompt))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.usage().orElse(null));
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)
}
modelInfo, err := client.Models.Get(ctx, "gemini-3.8-flash", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Input token limit: %d\n", modelInfo.InputTokenLimit)
fmt.Printf("Output token limit: %d\n", modelInfo.OutputTokenLimit)
}
REST
# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:countTokens" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"contents": [{"parts": [{"text": "The quick brown fox."}]}]}'
Đếm số token trong cuộc trò chuyện nhiều lượt
Đếm số mã thông báo trong nhật ký trò chuyện bằng previous_interaction_id:
Python
# This will only work for SDK newer than 2.0.0
# First interaction
interaction1 = client.interactions.create(
model="gemini-3.8-flash",
input="Hi, my name is Bob"
)
# Second interaction continues the conversation
interaction2 = client.interactions.create(
model="gemini-3.8-flash",
input="What's my name?",
previous_interaction_id=interaction1.id
)
# Usage includes tokens from both turns
print(f"Input tokens: {interaction2.usage.total_input_tokens}")
print(f"Output tokens: {interaction2.usage.total_output_tokens}")
print(f"Total tokens: {interaction2.usage.total_tokens}")
JavaScript
// This will only work for SDK newer than 2.0.0
// First interaction
const interaction1 = await client.interactions.create({
model: "gemini-3.8-flash",
input: "Hi, my name is Bob"
});
// Second interaction continues the conversation
const interaction2 = await client.interactions.create({
model: "gemini-3.8-flash",
input: "What's my name?",
previous_interaction_id: interaction1.id
});
console.log(`Input tokens: ${interaction2.usage.total_input_tokens}`);
console.log(`Output tokens: ${interaction2.usage.total_output_tokens}`);
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.Usage;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
// First interaction
CreateModelInteraction params1 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Hi, my name is Bob"))
.build();
Interaction interaction1 =
client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();
// Second interaction continues the conversation
CreateModelInteraction params2 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("What's my name?"))
.previousInteractionId(interaction1.id().orElse(""))
.build();
Interaction interaction2 =
client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();
// Usage includes tokens from both turns
if (interaction2.usage().isPresent()) {
Usage usage = interaction2.usage().get();
System.out.println("Input tokens: " + usage.totalInputTokens().orElse(0));
System.out.println("Output tokens: " + usage.totalOutputTokens().orElse(0));
System.out.println("Total tokens: " + usage.totalTokens().orElse(0));
}
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)
}
prompt := "The quick brown fox jumps over the lazy dog."
// Count input tokens before sending
totalTokens, err := client.Models.CountTokens(ctx, "gemini-3.8-flash", genai.Text(prompt), nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("total_tokens: %d\n", totalTokens.TotalTokens)
// Create the interaction and inspect the returned usage metadata
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput(prompt),
}),
})
if err != nil {
log.Fatal(err)
}
interaction := res.Interaction
if interaction.OutputText != nil {
fmt.Println(*interaction.OutputText)
}
if interaction.Usage != nil {
if interaction.Usage.TotalInputTokens != nil {
fmt.Printf("Input tokens: %d\n", *interaction.Usage.TotalInputTokens)
}
if interaction.Usage.TotalOutputTokens != nil {
fmt.Printf("Output tokens: %d\n", *interaction.Usage.TotalOutputTokens)
}
if interaction.Usage.TotalThoughtTokens != nil {
fmt.Printf("Thought tokens: %d\n", *interaction.Usage.TotalThoughtTokens)
}
if interaction.Usage.TotalTokens != nil {
fmt.Printf("Total tokens: %d\n", *interaction.Usage.TotalTokens)
}
}
}
Đếm mã thông báo đa phương thức
Tất cả dữ liệu đầu vào cho Gemini API đều được mã hoá thành mã thông báo, bao gồm cả hình ảnh, video và âm thanh. Những điểm chính về hoạt động mã hoá:
- Hình ảnh: Hình ảnh ≤384 pixel ở cả hai chiều được tính là 258 mã thông báo. Các hình ảnh lớn hơn được chia thành các ô có kích thước 768x768 pixel, mỗi ô được tính là 258 mã thông báo.
- Video: 263 token mỗi giây (áp dụng cho quá trình xử lý tĩnh). Đối với quá trình xử lý dựa trên tác nhân, mức sử dụng mã thông báo sẽ khác nhau. Xem phần Mức sử dụng mã thông báo video theo chế độ xử lý.
- Âm thanh: 32 token/giây
Mã thông báo hình ảnh
Python
# This will only work for SDK newer than 2.0.0
uploaded_file = client.files.upload(file="path/to/image.jpg")
# Count tokens for image + text
total_tokens = client.models.count_tokens(
model="gemini-3.8-flash",
contents=["Tell me about this image", uploaded_file]
)
print(f"Total tokens: {total_tokens}")
# Generate with image
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{"type": "text", "text": "Tell me about this image"},
{"type": "image", "uri": uploaded_file.uri, "mime_type": uploaded_file.mime_type}
]
)
print(interaction.usage)
JavaScript
// This will only work for SDK newer than 2.0.0
const uploadedFile = await client.files.upload({
file: "path/to/image.jpg",
config: { mimeType: "image/jpeg" }
});
// Count tokens
const countResponse = await client.models.countTokens({
model: "gemini-3.8-flash",
contents: [
{ text: "Tell me about this image" },
{ fileData: { fileUri: uploadedFile.uri, mimeType: uploadedFile.mimeType } }
]
});
console.log(countResponse.totalTokens);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
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.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.Content;
import com.google.genai.types.CountTokensResponse;
import com.google.genai.types.File;
import com.google.genai.types.Part;
import com.google.genai.types.UploadFileConfig;
import java.util.Arrays;
Client client = new Client();
File uploadedFile =
client.files.upload(
new java.io.File("path/to/image.jpg"),
UploadFileConfig.builder().mimeType("image/jpeg").build());
// Count tokens for image + text
CountTokensResponse countResponse =
client.models.countTokens(
"gemini-3.8-flash",
Arrays.asList(
Content.fromParts(
Part.fromText("Tell me about this image"),
Part.fromUri(
uploadedFile.uri().orElse(""), uploadedFile.mimeType().orElse("image/jpeg")))),
null);
System.out.println("Total tokens: " + countResponse.totalTokens().orElse(0));
// Generate with image
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(
InteractionsInput.ofContent(
Arrays.asList(
TextContent.builder().text("Tell me about this image").build(),
ImageContent.builder()
.uri(uploadedFile.uri().orElse(""))
.mimeType(
ImageContentMimeType.of(uploadedFile.mimeType().orElse("image/jpeg")))
.build())))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.usage().orElse(null));
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("Explain the history of the internet in 3 paragraphs."),
Stream: genai.Ptr(true),
}),
})
if err != nil {
log.Fatal(err)
}
stream := res.InteractionSSEStreamEvent
defer stream.Close()
for stream.Next() {
event := stream.Value()
if stepDelta := event.GetDataStepDelta(); stepDelta != nil {
if textDelta := stepDelta.GetDeltaText(); textDelta != nil {
fmt.Print(textDelta.GetText())
}
}
if completed := event.GetDataInteractionCompleted(); completed != nil {
usage := completed.Interaction.Usage
if usage != nil && usage.TotalTokens != nil {
fmt.Printf("\nTotal tokens: %d\n", *usage.TotalTokens)
}
}
}
if err := stream.Err(); err != nil {
log.Fatal(err)
}
}
Ví dụ về dữ liệu cùng dòng:
Python
# This will only work for SDK newer than 2.0.0
import base64
with open('image.jpg', 'rb') as f:
image_bytes = f.read()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{"type": "text", "text": "Describe this image"},
{
"type": "image",
"data": base64.b64encode(image_bytes).decode('utf-8'),
"mime_type": "image/jpeg"
}
]
)
print(interaction.usage)
Mã thông báo video
Python
# This will only work for SDK newer than 2.0.0
import time
video_file = client.files.upload(file="path/to/video.mp4")
while not video_file.state or video_file.state.name != "ACTIVE":
print("Processing video...")
time.sleep(5)
video_file = client.files.get(name=video_file.name)
# A 60-second video is approximately 100 * 60 = 6,000 tokens
total_tokens = client.models.count_tokens(
model="gemini-3.8-flash",
contents=["Summarize this video", video_file]
)
print(f"Total tokens: {total_tokens}")
# Generate with video
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{"type": "text", "text": "Summarize this video"},
{"type": "video", "uri": video_file.uri, "mime_type": video_file.mime_type}
]
)
print(interaction.usage)
Mức sử dụng mã thông báo video theo chế độ xử lý
Mức sử dụng mã thông báo cho video phụ thuộc vào chế độ xử lý:
| Chế độ xử lý | Cách tính số lượng mã thông báo | Cách sử dụng thông thường |
|---|---|---|
| Tĩnh (mặc định) | ~100 token/giây theo mặc định (độ phân giải thấp) hoặc ~300 token/giây (độ phân giải cao). Tất cả khung hình được lấy mẫu ở tốc độ 1 khung hình/giây. | Có thể dự đoán, tỷ lệ thuận với thời lượng video. |
| Tác nhân | Thay đổi tuỳ theo độ phức tạp của nội dung. Mô hình chỉ tải bản chép lời và/hoặc khung hình và/hoặc âm thanh cần thiết để trả lời câu lệnh. | Giảm tới 88% số lượng mã thông báo cho nội dung dài. |
Với quy trình xử lý tác nhân, một bài giảng dài 1 giờ sử dụng khoảng 1,08 triệu token ở chế độ tĩnh có thể chỉ sử dụng khoảng 108 nghìn token, tuỳ thuộc vào câu lệnh và nội dung.
Để kiểm tra mức sử dụng mã thông báo thực tế cho một yêu cầu, hãy kiểm tra interaction.usage. Mã thông báo video của tác nhân được báo cáo trên các trường sau:
- Câu lệnh ban đầu (video tham khảo + câu lệnh của người dùng):
total_input_tokens - Tư duy điều hướng:
total_thought_tokens - Bản chép lời, khung hình và âm thanh được tải theo yêu cầu:
total_tool_use_tokens - Câu trả lời cuối cùng:
total_output_tokens
Mã thông báo âm thanh
Python
# This will only work for SDK newer than 2.0.0
audio_file = client.files.upload(file="path/to/audio.mp3")
# A 60-second audio clip is approximately 32 * 60 = 1,920 tokens
total_tokens = client.models.count_tokens(
model="gemini-3.8-flash",
contents=["Transcribe this audio", audio_file]
)
print(f"Total tokens: {total_tokens}")
# Generate with audio
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{"type": "text", "text": "Transcribe this audio"},
{"type": "audio", "uri": audio_file.uri, "mime_type": audio_file.mime_type}
]
)
print(interaction.usage)
Đếm số mã thông báo chỉ dẫn hệ thống
Chỉ dẫn hệ thống được tính là một phần của mã thông báo đầu vào:
Python
# This will only work for SDK newer than 2.0.0
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Hello!",
system_instruction="You are a helpful assistant who speaks like a pirate."
)
# system_instruction tokens included in total_input_tokens
print(f"Input tokens: {interaction.usage.total_input_tokens}")
Đếm số token công cụ
Các công cụ (hàm, thực thi mã, Google Tìm kiếm) cũng được tính:
Python
# This will only work for SDK newer than 2.0.0
tools = [
{
"type": "function",
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
}
}
}
]
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="What's the weather in Tokyo?",
tools=tools
)
print(f"Input tokens: {interaction.usage.total_input_tokens}")
print(f"Tool use tokens: {interaction.usage.total_tool_use_tokens}")
Cửa sổ ngữ cảnh
Mỗi mô hình Gemini đều có số lượng mã thông báo tối đa mà mô hình đó có thể xử lý.
- Các mô hình Gemini 4 (
gemini-4-argon): Dùng chung một cửa sổ ngữ cảnh 1 triệu token (1,048,576token) cho cả token đầu vào, token tư duy và token đầu ra. Theo mặc định, các câu trả lời đồng bộ (background=False, truyền trực tuyến hoặc không truyền trực tuyến) bị giới hạn ở65,536mã thông báo đầu ra hoặc bạn có thể tạo tối đa1,048,576mã thông báo bằng cách sử dụng giải mã dài. Nếu số token đầu vào cộng vớimax_output_tokensvượt quá 1.048.576 token, thì API sẽ tự động giới hạn đầu ra ở mức không gian còn lại trong cửa sổ ngữ cảnh (1,048,576trừ đi số token đầu vào). - Các mô hình Gemini 3 và 2.5: Sử dụng ngân sách riêng cho đầu vào (
1,048,576token) và đầu ra (65,536token).
Lấy kích thước cửa sổ ngữ cảnh theo phương thức lập trình
Python
# This will only work for SDK newer than 2.0.0
model_info = client.models.get(model="gemini-3.8-flash")
print(f"Input token limit: {model_info.input_token_limit}")
print(f"Output token limit: {model_info.output_token_limit}")
JavaScript
// This will only work for SDK newer than 2.0.0
const modelInfo = await client.models.get({ model: "gemini-3.8-flash" });
console.log(`Input token limit: ${modelInfo.inputTokenLimit}`);
console.log(`Output token limit: ${modelInfo.outputTokenLimit}`);
Java
import com.google.genai.Client;
import com.google.genai.types.Model;
Client client = new Client();
Model modelInfo = client.models.get("gemini-3.8-flash", null);
System.out.println("Input token limit: " + modelInfo.inputTokenLimit().orElse(0));
System.out.println("Output token limit: " + modelInfo.outputTokenLimit().orElse(0));
Go
package main
import (
"context"
"encoding/base64"
"fmt"
"log"
"os"
"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)
}
prompt := "Tell me about this instrument"
imageBytes, err := os.ReadFile("/path/to/organ.jpg")
if err != nil {
log.Fatal(err)
}
base64Image := base64.StdEncoding.EncodeToString(imageBytes)
// Count tokens before creating the interaction
parts := []*genai.Part{
genai.NewPartFromText(prompt),
genai.NewPartFromBytes(imageBytes, "image/jpeg"),
}
totalTokens, err := client.Models.CountTokens(ctx, "gemini-3.8-flash", []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}, nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Estimated input tokens: %d\n", totalTokens.TotalTokens)
// Create the multimodal interaction and inspect the usage metadata
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput([]interactions.Content{
interactions.NewContent(interactions.TextContent{
Text: prompt,
}),
interactions.NewContent(interactions.ImageContent{
Data: genai.Ptr(base64Image),
MimeType: interactions.ImageContentMimeTypeImageJpeg.ToPointer(),
}),
}),
}),
})
if err != nil {
log.Fatal(err)
}
interaction := res.Interaction
if interaction.OutputText != nil {
fmt.Println(*interaction.OutputText)
}
if interaction.Usage != nil && interaction.Usage.TotalTokens != nil {
fmt.Printf("Total tokens billed: %d\n", *interaction.Usage.TotalTokens)
}
}
Tìm kích thước cửa sổ ngữ cảnh trên trang mô hình.
Bước tiếp theo
- Tạo văn bản: Kiến thức cơ bản về tạo văn bản
- Lưu vào bộ nhớ đệm: Giảm chi phí bằng cách lưu vào bộ nhớ đệm
- Định giá: Tìm hiểu về chi phí