列出及計算符記

本頁面說明如何列出提示的符記和符記 ID,以及如何使用 Google Gen AI SDK 取得提示的符記總數。

符記和符記列舉與計數的重要性

生成式 AI 模型會將提示中的文字和其他資料拆解成較小的單元,稱為「符記」,以便處理。資料轉換為符記的方式取決於所使用的分詞器。符記可以是字元、字詞或詞組。

每個模型在提示和回覆中可處理的符記數量有上限。瞭解提示的符記數量,即可得知是否已超出此限制。此外,計數符記也會傳回提示的可計費字元,協助您估算費用。

列出符號會傳回提示內容拆分後的符號清單。每個列出的符記都會與符記 ID 相關聯,方便您進行疑難排解及分析模型行為。

支援的模型

下表列出支援符記清單和符記計數的模型:

取得提示的符記和符記 ID 清單

下列程式碼範例示範如何取得提示的符記和符記 ID 清單。提示只能包含文字。不支援多模態提示。

Gen AI SDK for Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.compute_tokens(
    model="gemini-2.5-flash",
    contents="What's the longest word in the English language?",
)

print(response)
# Example output:
# tokens_info=[TokensInfo(
#    role='user',
#    token_ids=[1841, 235303, 235256, 573, 32514, 2204, 575, 573, 4645, 5255, 235336],
#    tokens=[b'What', b"'", b's', b' the', b' longest', b' word', b' in', b' the', b' English', b' language', b'?']
#  )]

Gen AI SDK for Go

瞭解如何安裝或更新 Gen AI SDK for Go

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// computeWithTxt shows how to compute tokens with text input.
func computeWithTxt(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What's the longest word in the English language?"},
		}},
	}

	resp, err := client.Models.ComputeTokens(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	type tokenInfoDisplay struct {
		IDs    []int64  `json:"token_ids"`
		Tokens []string `json:"tokens"`
	}
	// See the documentation: https://pkg.go.dev/google.golang.org/genai#ComputeTokensResponse
	for _, instance := range resp.TokensInfo {
		display := tokenInfoDisplay{
			IDs:    instance.TokenIDs,
			Tokens: make([]string, len(instance.Tokens)),
		}
		for i, t := range instance.Tokens {
			display.Tokens[i] = string(t)
		}

		data, err := json.MarshalIndent(display, "", "  ")
		if err != nil {
			return fmt.Errorf("failed to marshal token info: %w", err)
		}
		fmt.Fprintln(w, string(data))
	}

	// Example response:
	// {
	// 	"ids": [
	// 		1841,
	// 		235303,
	// 		235256,
	//    ...
	// 	],
	// 	"values": [
	// 		"What",
	// 		"'",
	// 		"s",
	//    ...
	// 	]
	// }

	return nil
}

取得提示的符號數量和計費字元

下列程式碼範例說明如何取得符記數量,以及提示的可計費字元數量。系統支援純文字和多模態提示。

Gen AI SDK for Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))

prompt = "Why is the sky blue?"

# Send text to Gemini
response = client.models.generate_content(
    model="gemini-2.5-flash", contents=prompt
)

# Prompt and response tokens count
print(response.usage_metadata)

# Example output:
#  cached_content_token_count=None
#  candidates_token_count=311
#  prompt_token_count=6
#  total_token_count=317

Gen AI SDK for Go

瞭解如何安裝或更新 Gen AI SDK for Go

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateTextAndCount shows how to generate text and obtain token count metadata from the model response.
func generateTextAndCount(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "Why is the sky blue?"},
		}},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	usage, err := json.MarshalIndent(resp.UsageMetadata, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to convert usage metadata to JSON: %w", err)
	}
	fmt.Fprintln(w, string(usage))

	// Example response:
	// {
	// 	 "candidatesTokenCount": 339,
	// 	 "promptTokenCount": 6,
	// 	 "totalTokenCount": 345
	// }

	return nil
}