ทําความเข้าใจและนับโทเค็น

Gemini และโมเดล Generative AI อื่นๆ จะประมวลผลอินพุตและเอาต์พุตที่ระดับความละเอียด ที่เรียกว่าโทเค็น

สำหรับโมเดล Gemini โทเค็นจะเท่ากับอักขระประมาณ 4 ตัว โดย 100 โทเค็นจะเท่ากับคำภาษาอังกฤษประมาณ 60-80 คำ

เกี่ยวกับโทเค็น

โทเค็นอาจเป็นอักขระเดียว เช่น z หรือทั้งคำ เช่น cat ระบบจะแบ่งคำยาวๆ ออกเป็นหลายโทเค็น ชุดโทเค็นทั้งหมดที่โมเดลใช้เรียกว่า คำศัพท์ และกระบวนการแยกข้อความเป็นโทเค็นเรียกว่า การโทเค็น

เมื่อเปิดใช้การเรียกเก็บเงิน ค่าใช้จ่ายในการเรียกใช้ Gemini API จะขึ้นอยู่กับจำนวนโทเค็นอินพุตและเอาต์พุตบางส่วน ดังนั้นการรู้วิธีนับโทเค็นจึงอาจเป็นประโยชน์

คุณลองนับโทเค็นใน Colab ของเราได้

ดูที่ ai.google.dev ลองใช้ Colab Notebook ดูสมุดบันทึกใน GitHub

นับโทเค็น

อินพุตทั้งหมดที่ส่งไปยังและเอาต์พุตทั้งหมดที่ได้รับจาก Gemini API จะได้รับการโทเค็น รวมถึงข้อความ ไฟล์รูปภาพ และรูปแบบอื่นๆ ที่ไม่ใช่ข้อความ

คุณนับโทเค็นได้ด้วยวิธีต่อไปนี้

  • โทรหา count_tokens พร้อมอินพุต ของคำขอ
    ฟังก์ชันนี้จะแสดงผลจำนวนโทเค็นทั้งหมดในอินพุตเท่านั้น คุณสามารถเรียกใช้ฟังก์ชันนี้ก่อนส่งอินพุตไปยังโมเดลเพื่อตรวจสอบขนาดของคำขอได้

  • ใช้แอตทริบิวต์ usage_metadata ในออบเจ็กต์ response หลังจาก เรียกใช้ generate_content
    ซึ่งจะแสดงผลจำนวนโทเค็นทั้งหมดtotal_token_countทั้งในอินพุตและเอาต์พุต
    นอกจากนี้ยังแสดงผลจำนวนโทเค็นของอินพุตและเอาต์พุตแยกกันด้วย prompt_token_count (โทเค็นอินพุต) และ candidates_token_count (โทเค็นเอาต์พุต)

    หากคุณใช้โมเดลการคิด ระบบจะส่งโทเค็นที่ใช้ในระหว่างกระบวนการคิด กลับมาใน thoughts_token_count และหากคุณใช้การแคชบริบท จำนวนโทเค็นที่แคชไว้จะอยู่ใน cached_content_token_count

นับโทเค็นข้อความ

หากเรียกใช้ count_tokens ด้วยอินพุตที่เป็นข้อความเท่านั้น ระบบจะแสดงผลจำนวนโทเค็นของข้อความในอินพุตเท่านั้น (total_tokens) คุณสามารถเรียกใช้ฟังก์ชันนี้ก่อนเรียกใช้ generate_content เพื่อตรวจสอบขนาดของคำขอได้

อีกทางเลือกหนึ่งคือการเรียก generate_content แล้วใช้แอตทริบิวต์ usage_metadata ในออบเจ็กต์ response เพื่อรับข้อมูลต่อไปนี้

  • จำนวนโทเค็นแยกกันของอินพุต (prompt_token_count) เนื้อหาที่แคช (cached_content_token_count) และเอาต์พุต (candidates_token_count)
  • จำนวนโทเค็นสำหรับกระบวนการคิด (thoughts_token_count)
  • จำนวนโทเค็นทั้งหมดทั้งในอินพุตและเอาต์พุต (total_token_count)

Python

from google import genai

client = genai.Client()
prompt = "The quick brown fox jumps over the lazy dog."

total_tokens = client.models.count_tokens(
    model="gemini-3-flash-preview", contents=prompt
)
print("total_tokens: ", total_tokens)

response = client.models.generate_content(
    model="gemini-3-flash-preview", contents=prompt
)

print(response.usage_metadata)

JavaScript

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

const ai = new GoogleGenAI({});
const prompt = "The quick brown fox jumps over the lazy dog.";

async function main() {
  const countTokensResponse = await ai.models.countTokens({
    model: "gemini-3-flash-preview",
    contents: prompt,
  });
  console.log(countTokensResponse.totalTokens);

  const generateResponse = await ai.models.generateContent({
    model: "gemini-3-flash-preview",
    contents: prompt,
  });
  console.log(generateResponse.usageMetadata);
}

await main();

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)

// Convert prompt to a slice of *genai.Content using the helper.
contents := []*genai.Content{
  genai.NewContentFromText(prompt, genai.RoleUser),
}
countResp, err := client.Models.CountTokens(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  return err
}
fmt.Println("total_tokens:", countResp.TotalTokens)

response, err := client.Models.GenerateContent(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  log.Fatal(err)
}
usageMetadata, err := json.MarshalIndent(response.UsageMetadata, "", "  ")
if err != nil {
  log.Fatal(err)
}
fmt.Println(string(usageMetadata))
    ```

นับโทเค็นแบบหลายรอบ (แชท)

หากคุณเรียกใช้ count_tokens พร้อมประวัติการแชท ระบบจะแสดงผลจำนวนโทเค็นทั้งหมด ของข้อความจากแต่ละบทบาทในการแชท (total_tokens)

อีกทางเลือกหนึ่งคือการเรียก send_message แล้วใช้แอตทริบิวต์ usage_metadata ในออบเจ็กต์ response เพื่อรับข้อมูลต่อไปนี้

  • จำนวนโทเค็นแยกกันของอินพุต (prompt_token_count) เนื้อหาที่แคช (cached_content_token_count) และเอาต์พุต (candidates_token_count)
  • จำนวนโทเค็นสำหรับกระบวนการคิด (thoughts_token_count)
  • จำนวนโทเค็นทั้งหมดทั้งในอินพุตและเอาต์พุต (total_token_count)

หากต้องการทราบว่าการสนทนาครั้งถัดไปจะมีขนาดเท่าใด คุณต้องต่อท้าย การสนทนาครั้งก่อนเมื่อเรียกใช้ count_tokens

Python

from google import genai
from google.genai import types

client = genai.Client()

chat = client.chats.create(
    model="gemini-3-flash-preview",
    history=[
        types.Content(
            role="user", parts=[types.Part(text="Hi my name is Bob")]
        ),
        types.Content(role="model", parts=[types.Part(text="Hi Bob!")]),
    ],
)

print(
    client.models.count_tokens(
        model="gemini-3-flash-preview", contents=chat.get_history()
    )
)

response = chat.send_message(
    message="In one sentence, explain how a computer works to a young child."
)
print(response.usage_metadata)

extra = types.UserContent(
    parts=[
        types.Part(
            text="What is the meaning of life?",
        )
    ]
)
history = [*chat.get_history(), extra]
print(client.models.count_tokens(model="gemini-3-flash-preview", contents=history))

JavaScript

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

const ai = new GoogleGenAI({});

async function main() {
  const history = [
    { role: "user", parts: [{ text: "Hi my name is Bob" }] },
    { role: "model", parts: [{ text: "Hi Bob!" }] },
  ];
  const chat = ai.chats.create({
    model: "gemini-3-flash-preview",
    history: history,
  });

  const countTokensResponse = await ai.models.countTokens({
    model: "gemini-3-flash-preview",
    contents: chat.getHistory(),
  });
  console.log(countTokensResponse.totalTokens);

  const chatResponse = await chat.sendMessage({
    message: "In one sentence, explain how a computer works to a young child.",
  });
  console.log(chatResponse.usageMetadata);

  const extraMessage = {
    role: "user",
    parts: [{ text: "What is the meaning of life?" }],
  };
  const combinedHistory = [...chat.getHistory(), extraMessage];
  const combinedCountTokensResponse = await ai.models.countTokens({
    model: "gemini-3-flash-preview",
    contents: combinedHistory,
  });
  console.log(
    "Combined history token count:",
    combinedCountTokensResponse.totalTokens,
  );
}

await main();

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)

history := []*genai.Content{
  {Role: genai.RoleUser, Parts: []*genai.Part({Text: "Hi my name is Bob"})},
  {Role: genai.RoleModel, Parts: []*genai.Part({Text: "Hi Bob!"})},
}
chat, err := client.Chats.Create(ctx, "gemini-3-flash-preview", nil, history)
if err != nil {
  log.Fatal(err)
}

firstTokenResp, err := client.Models.CountTokens(ctx, "gemini-3-flash-preview", chat.History(false), nil)
if err != nil {
  log.Fatal(err)
}
fmt.Println(firstTokenResp.TotalTokens)

resp, err := chat.SendMessage(ctx, genai.NewPartFromText("In one sentence, explain how a computer works to a young child."))
if err != nil {
  log.Fatal(err)
}
fmt.Printf("%#v\n", resp.UsageMetadata)

extra := genai.NewContentFromText("What is the meaning of life?", genai.RoleUser)
hist := chat.History(false)
hist = append(hist, extra)

secondTokenResp, err := client.Models.CountTokens(ctx, "gemini-3-flash-preview", hist, nil)
if err != nil {
  log.Fatal(err)
}
fmt.Println(secondTokenResp.TotalTokens)

นับโทเค็นหลายรูปแบบ

อินพุตทั้งหมดไปยัง Gemini API จะได้รับการโทเค็น รวมถึงข้อความ ไฟล์รูปภาพ และรูปแบบอื่นๆ ที่ไม่ใช่ข้อความ โปรดทราบประเด็นสำคัญระดับสูงต่อไปนี้เกี่ยวกับการแปลงอินพุตมัลติโมดัลเป็นโทเค็น ระหว่างการประมวลผลโดย Gemini API

  • อินพุตรูปภาพที่มีทั้ง 2 มิติ <=384 พิกเซลจะนับเป็น 258 โทเค็น รูปภาพที่มีขนาดใหญ่กว่าในมิติใดมิติหนึ่งหรือทั้ง 2 มิติจะถูกครอบตัดและปรับขนาดตาม ความจำเป็นเป็นไทล์ขนาด 768x768 พิกเซล โดยแต่ละไทล์จะนับเป็น 258 โทเค็น

  • ระบบจะแปลงไฟล์วิดีโอและเสียงเป็นโทเค็นในอัตราคงที่ต่อไปนี้ วิดีโอที่ 263 โทเค็นต่อวินาที และเสียงที่ 32 โทเค็นต่อวินาที

ความละเอียดของสื่อ

โมเดล Gemini 3 มีการควบคุมแบบละเอียดในการประมวลผลวิชันซิสเต็มหลายรูปแบบด้วยพารามิเตอร์ media_resolution พารามิเตอร์ media_resolution จะกำหนดจำนวนโทเค็นสูงสุดที่จัดสรรต่อรูปภาพอินพุตหรือเฟรมวิดีโอ ความละเอียดที่สูงขึ้นจะช่วยปรับปรุงความสามารถของโมเดลในการอ่านข้อความขนาดเล็กหรือระบุรายละเอียดเล็กๆ แต่จะเพิ่มการใช้โทเค็นและเวลาในการตอบสนอง

ดูรายละเอียดเพิ่มเติมเกี่ยวกับพารามิเตอร์และผลกระทบที่อาจมีต่อการคำนวณโทเค็นได้ที่คู่มือความละเอียดของสื่อ

ไฟล์ภาพ

หากเรียกใช้ count_tokens ด้วยอินพุตข้อความและรูปภาพ ระบบจะแสดงผลจำนวนโทเค็นรวมของข้อความและรูปภาพในอินพุตเท่านั้น (total_tokens) คุณ สามารถเรียกใช้ฟังก์ชันนี้ก่อนเรียกใช้ generate_content เพื่อตรวจสอบขนาดของคำขอ ได้ นอกจากนี้ คุณยังเรียกใช้ count_tokens ในข้อความและไฟล์ แยกกันได้ด้วย

อีกทางเลือกหนึ่งคือการเรียก generate_content แล้วใช้แอตทริบิวต์ usage_metadata ในออบเจ็กต์ response เพื่อรับข้อมูลต่อไปนี้

  • จำนวนโทเค็นแยกกันของอินพุต (prompt_token_count) เนื้อหาที่แคช (cached_content_token_count) และเอาต์พุต (candidates_token_count)
  • จำนวนโทเค็นสำหรับกระบวนการคิด (thoughts_token_count)
  • จำนวนโทเค็นทั้งหมดทั้งในอินพุตและเอาต์พุต (total_token_count)

ตัวอย่างที่ใช้รูปภาพที่อัปโหลดจาก File API

Python

from google import genai

client = genai.Client()
prompt = "Tell me about this image"
your_image_file = client.files.upload(file=media / "organ.jpg")

print(
    client.models.count_tokens(
        model="gemini-3-flash-preview", contents=[prompt, your_image_file]
    )
)

response = client.models.generate_content(
    model="gemini-3-flash-preview", contents=[prompt, your_image_file]
)
print(response.usage_metadata)

JavaScript

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

const ai = new GoogleGenAI({});
const prompt = "Tell me about this image";

async function main() {
  const organ = await ai.files.upload({
    file: path.join(media, "organ.jpg"),
    config: { mimeType: "image/jpeg" },
  });

  const countTokensResponse = await ai.models.countTokens({
    model: "gemini-3-flash-preview",
    contents: createUserContent([
      prompt,
      createPartFromUri(organ.uri, organ.mimeType),
    ]),
  });
  console.log(countTokensResponse.totalTokens);

  const generateResponse = await ai.models.generateContent({
    model: "gemini-3-flash-preview",
    contents: createUserContent([
      prompt,
      createPartFromUri(organ.uri, organ.mimeType),
    ]),
  });
  console.log(generateResponse.usageMetadata);
}

await main();

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)

file, err := client.Files.UploadFromPath(
  ctx, 
  filepath.Join(getMedia(), "organ.jpg"), 
  &genai.UploadFileConfig{
    MIMEType : "image/jpeg",
  },
)
if err != nil {
  log.Fatal(err)
}
parts := []*genai.Part{
  genai.NewPartFromText("Tell me about this image"),
  genai.NewPartFromURI(file.URI, file.MIMEType),
}
contents := []*genai.Content{
  genai.NewContentFromParts(parts, genai.RoleUser),
}

tokenResp, err := client.Models.CountTokens(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  log.Fatal(err)
}
fmt.Println("Multimodal image token count:", tokenResp.TotalTokens)

response, err := client.Models.GenerateContent(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  log.Fatal(err)
}
usageMetadata, err := json.MarshalIndent(response.UsageMetadata, "", "  ")
if err != nil {
  log.Fatal(err)
}
fmt.Println(string(usageMetadata))

ตัวอย่างที่แสดงรูปภาพเป็นข้อมูลแบบอินไลน์

Python

from google import genai
import PIL.Image

client = genai.Client()
prompt = "Tell me about this image"
your_image_file = PIL.Image.open(media / "organ.jpg")

print(
    client.models.count_tokens(
        model="gemini-3-flash-preview", contents=[prompt, your_image_file]
    )
)

response = client.models.generate_content(
    model="gemini-3-flash-preview", contents=[prompt, your_image_file]
)
print(response.usage_metadata)

JavaScript

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

const ai = new GoogleGenAI({});
const prompt = "Tell me about this image";
const imageBuffer = fs.readFileSync(path.join(media, "organ.jpg"));

const imageBase64 = imageBuffer.toString("base64");

const contents = createUserContent([
  prompt,
  createPartFromBase64(imageBase64, "image/jpeg"),
]);

async function main() {
  const countTokensResponse = await ai.models.countTokens({
    model: "gemini-3-flash-preview",
    contents: contents,
  });
  console.log(countTokensResponse.totalTokens);

  const generateResponse = await ai.models.generateContent({
    model: "gemini-3-flash-preview",
    contents: contents,
  });
  console.log(generateResponse.usageMetadata);
}

await main();

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)

imageBytes, err := os.ReadFile("organ.jpg")
if err != nil {
    log.Fatalf("Failed to read image file: %v", err)
}
parts := []*genai.Part{
  genai.NewPartFromText("Tell me about this image"),
  {
        InlineData: &genai.Blob{
              MIMEType: "image/jpeg",
              Data:     imageBytes,
        },
  },
}
contents := []*genai.Content{
  genai.NewContentFromParts(parts, genai.RoleUser),
}

tokenResp, err := client.Models.CountTokens(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  log.Fatal(err)
}
fmt.Println("Multimodal image token count:", tokenResp.TotalTokens)

response, err := client.Models.GenerateContent(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  log.Fatal(err)
}
usageMetadata, err := json.MarshalIndent(response.UsageMetadata, "", "  ")
if err != nil {
  log.Fatal(err)
}
fmt.Println(string(usageMetadata))

ไฟล์วิดีโอหรือเสียง

ระบบจะแปลงเสียงและวิดีโอแต่ละรายการเป็นโทเค็นในอัตราคงที่ต่อไปนี้

  • วิดีโอ: 263 โทเค็นต่อวินาที
  • เสียง: 32 โทเค็นต่อวินาที

หากเรียกใช้ count_tokens ด้วยอินพุตข้อความและวิดีโอ/เสียง ระบบจะแสดงจำนวนโทเค็นรวมของข้อความและไฟล์วิดีโอ/เสียงในอินพุตเท่านั้น (total_tokens) คุณสามารถเรียกใช้ฟังก์ชันนี้ก่อนเรียกใช้ generate_content เพื่อ ตรวจสอบขนาดของคำขอได้ นอกจากนี้ คุณยังเรียกใช้ count_tokens ใน ข้อความและไฟล์แยกกันได้ด้วย

อีกทางเลือกหนึ่งคือการเรียก generate_content แล้วใช้แอตทริบิวต์ usage_metadata ในออบเจ็กต์ response เพื่อรับข้อมูลต่อไปนี้

  • จำนวนโทเค็นแยกกันของอินพุต (prompt_token_count) เนื้อหาที่แคช (cached_content_token_count) และเอาต์พุต (candidates_token_count)
  • จำนวนโทเค็นสำหรับกระบวนการคิด (thoughts_token_count)
  • จำนวนโทเค็นทั้งหมดทั้งในอินพุตและเอาต์พุต (total_token_count)

Python

from google import genai
import time

client = genai.Client()
prompt = "Tell me about this video"
your_file = client.files.upload(file=media / "Big_Buck_Bunny.mp4")

while not your_file.state or your_file.state.name != "ACTIVE":
    print("Processing video...")
    print("File state:", your_file.state)
    time.sleep(5)
    your_file = client.files.get(name=your_file.name)

print(
    client.models.count_tokens(
        model="gemini-3-flash-preview", contents=[prompt, your_file]
    )
)

response = client.models.generate_content(
    model="gemini-3-flash-preview", contents=[prompt, your_file]
)
print(response.usage_metadata)

JavaScript

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

const ai = new GoogleGenAI({});
const prompt = "Tell me about this video";

async function main() {
  let videoFile = await ai.files.upload({
    file: path.join(media, "Big_Buck_Bunny.mp4"),
    config: { mimeType: "video/mp4" },
  });

  while (!videoFile.state || videoFile.state.toString() !== "ACTIVE") {
    console.log("Processing video...");
    console.log("File state: ", videoFile.state);
    await sleep(5000);
    videoFile = await ai.files.get({ name: videoFile.name });
  }

  const countTokensResponse = await ai.models.countTokens({
    model: "gemini-3-flash-preview",
    contents: createUserContent([
      prompt,
      createPartFromUri(videoFile.uri, videoFile.mimeType),
    ]),
  });
  console.log(countTokensResponse.totalTokens);

  const generateResponse = await ai.models.generateContent({
    model: "gemini-3-flash-preview",
    contents: createUserContent([
      prompt,
      createPartFromUri(videoFile.uri, videoFile.mimeType),
    ]),
  });
  console.log(generateResponse.usageMetadata);
}

await main();

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)

file, err := client.Files.UploadFromPath(
  ctx,
  filepath.Join(getMedia(), "Big_Buck_Bunny.mp4"),
  &genai.UploadFileConfig{
    MIMEType : "video/mp4",
  },
)
if err != nil {
  log.Fatal(err)
}

for file.State == genai.FileStateUnspecified || file.State != genai.FileStateActive {
  fmt.Println("Processing video...")
  fmt.Println("File state:", file.State)
  time.Sleep(5 * time.Second)

  file, err = client.Files.Get(ctx, file.Name, nil)
  if err != nil {
    log.Fatal(err)
  }
}

parts := []*genai.Part{
  genai.NewPartFromText("Tell me about this video"),
  genai.NewPartFromURI(file.URI, file.MIMEType),
}
contents := []*genai.Content{
  genai.NewContentFromParts(parts, genai.RoleUser),
}

tokenResp, err := client.Models.CountTokens(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  log.Fatal(err)
}
fmt.Println("Multimodal video/audio token count:", tokenResp.TotalTokens)
response, err := client.Models.GenerateContent(ctx, "gemini-3-flash-preview", contents, nil)
if err != nil {
  log.Fatal(err)
}
usageMetadata, err := json.MarshalIndent(response.UsageMetadata, "", "  ")
if err != nil {
  log.Fatal(err)
}
fmt.Println(string(usageMetadata))

หน้าต่างบริบท

โมเดลที่พร้อมใช้งานผ่าน Gemini API มีหน้าต่างบริบทที่วัดเป็นโทเค็น หน้าต่างบริบทจะกำหนดปริมาณอินพุตที่คุณระบุได้ และปริมาณเอาต์พุตที่โมเดลสร้างได้ คุณกำหนดขนาดของ หน้าต่างบริบทได้โดยเรียกใช้models.getปลายทาง หรือดูในเอกสารประกอบของโมเดล

Python

from google import genai

client = genai.Client()
model_info = client.models.get(model="gemini-3-flash-preview")
print(f"{model_info.input_token_limit=}")
print(f"{model_info.output_token_limit=}")

JavaScript

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

const ai = new GoogleGenAI({});

async function main() {
  const modelInfo = await ai.models.get({model: 'gemini-3-flash-preview'});
  console.log(modelInfo.inputTokenLimit);
  console.log(modelInfo.outputTokenLimit);
}

await main();

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
  log.Fatal(err)
}
modelInfo, err := client.ModelInfo(ctx, "models/gemini-3-flash-preview")
if err != nil {
  log.Fatal(err)
}
fmt.Println("input token limit:", modelInfo.InputTokenLimit)
fmt.Println("output token limit:", modelInfo.OutputTokenLimit)