토큰 집계 API 사용

이 페이지에서는 countTokens API를 사용하여 프롬프트의 토큰 수와 청구 가능한 문자 수를 가져오는 방법을 보여줍니다.

지원되는 모델

다음 멀티모달 모델은 프롬프트 토큰 수 추정치를 가져올 수 있습니다.

모델 버전에 대한 자세한 내용은 Gemini 모델 버전 및 수명 주기를 참조하세요.

프롬프트의 토큰 수 가져오기

Vertex AI API를 사용하여 프롬프트의 토큰 예측 수와 청구 가능한 문자 수를 가져올 수 있습니다.

콘솔

Google Cloud 콘솔에서 Vertex AI Studio를 사용하여 프롬프트의 토큰 수를 가져오려면 다음 단계를 수행합니다.

  1. 콘솔의 Vertex AI 섹션에서 Google Cloud Vertex AI Studio 페이지로 이동합니다.

    Vertex AI Studio로 이동

  2. 자유 형식 열기 또는 Chat 열기를 클릭합니다.
  3. 토큰 수는 프롬프트 창에 입력할 때 계산되어 표시됩니다. 입력 파일의 토큰 수가 포함됩니다.
  4. 자세한 내용을 보려면 <count> 토큰을 클릭하여 프롬프트 토크나이저를 엽니다.
    • 텍스트 프롬프트에서 각 토큰 ID의 경계를 표시하는 다양한 색상으로 강조표시된 토큰을 보려면 토큰 ID 텍스트로 변환을 클릭합니다. 미디어 토큰은 지원되지 않습니다.
    • 토큰 ID를 보려면 토큰 ID를 클릭합니다.

      토크나이저 도구 창을 닫으려면 X를 클릭하거나 창 바깥쪽을 클릭합니다.

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.count_tokens(
    model="gemini-2.5-flash",
    contents="What's the highest mountain in Africa?",
)
print(response)
# Example output:
# total_tokens=10
# cached_content_token_count=None

Go

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"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// countWithTxt shows how to count tokens with text input.
func countWithTxt(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.5-flash"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What's the highest mountain in Africa?"},
		}},
	}

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

	fmt.Fprintf(w, "Total: %d\nCached: %d\n", resp.TotalTokens, resp.CachedContentTokenCount)

	// Example response:
	// Total: 9
	// Cached: 0

	return nil
}

Node.js

설치

npm install @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

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function countTokens(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const ai = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await ai.models.countTokens({
    model: 'gemini-2.5-flash',
    contents: 'What is the highest mountain in Africa?',
  });

  console.log(response);

  return response.totalTokens;
}

Java

Java를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 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 com.google.genai.Client;
import com.google.genai.types.CountTokensResponse;
import com.google.genai.types.HttpOptions;
import java.util.Optional;

public class CountTokensWithText {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    countTokens(modelId);
  }

  // Counts tokens with text input
  public static Optional<Integer> countTokens(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      CountTokensResponse response =
          client.models.countTokens(modelId, "What's the highest mountain in Africa?", null);

      System.out.print(response);
      // Example response:
      // CountTokensResponse{totalTokens=Optional[9], cachedContentTokenCount=Optional.empty}
      return response.totalTokens();
    }
  }
}

REST

Vertex AI API를 사용해서 프롬프트에 대해 토큰 수 및 청구 가능한 문자 수를 가져오려면 게시자 모델 엔드포인트에 POST 요청을 전송합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 요청을 처리하는 리전입니다. 사용 가능한 옵션은 다음과 같습니다.

    클릭하여 사용 가능한 리전의 일부 목록 펼치기

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID: 프로젝트 ID입니다.
  • MODEL_ID: 사용할 멀티모달 모델의 모델 ID입니다.
  • ROLE: 콘텐츠와 연결된 대화의 역할입니다. 싱글턴 사용 사례에서도 역할을 지정해야 합니다. 허용되는 값은 다음과 같습니다.
    • USER: 전송한 콘텐츠를 지정합니다.
  • TEXT: 프롬프트에 포함할 텍스트 안내입니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:countTokens

JSON 요청 본문:

{
  "contents": [{
    "role": "ROLE",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:countTokens"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:countTokens" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 수신됩니다.

이미지 또는 동영상이 포함된 텍스트의 예시:

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, Part

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

contents = [
    Part.from_uri(
        file_uri="gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
        mime_type="video/mp4",
    ),
    "Provide a description of the video.",
]

response = client.models.count_tokens(
    model="gemini-2.5-flash",
    contents=contents,
)
print(response)
# Example output:
# total_tokens=16252 cached_content_token_count=None

Go

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"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// countWithTxtAndVid shows how to count tokens with text and video inputs.
func countWithTxtAndVid(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.5-flash"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "Provide a description of the video."},
			{FileData: &genai.FileData{
				FileURI:  "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
				MIMEType: "video/mp4",
			}},
		},
			Role: "user"},
	}

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

	fmt.Fprintf(w, "Total: %d\nCached: %d\n", resp.TotalTokens, resp.CachedContentTokenCount)

	// Example response:
	// Total: 16252
	// Cached: 0

	return nil
}

Node.js

설치

npm install @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

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function countTokens(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const ai = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const video = {
    fileData: {
      fileUri: 'gs://cloud-samples-data/generative-ai/video/pixel8.mp4',
      mimeType: 'video/mp4',
    },
  };

  const response = await ai.models.countTokens({
    model: 'gemini-2.5-flash',
    contents: [video, 'Provide a description of the video.'],
  });

  console.log(response);

  return response.totalTokens;
}

Java

Java를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 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 com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.CountTokensResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;
import java.util.List;
import java.util.Optional;

public class CountTokensWithTextAndVideo {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    countTokens(modelId);
  }

  // Counts tokens with text and video inputs
  public static Optional<Integer> countTokens(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      Content content =
          Content.fromParts(
              Part.fromText("Provide a description of this video"),
              Part.fromUri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4", "video/mp4"));

      CountTokensResponse response = client.models.countTokens(modelId, List.of(content), null);

      System.out.print(response);
      // Example response:
      // CountTokensResponse{totalTokens=Optional[16707], cachedContentTokenCount=Optional.empty}
      return response.totalTokens();
    }
  }
}

REST

Vertex AI API를 사용해서 프롬프트에 대해 토큰 수 및 청구 가능한 문자 수를 가져오려면 게시자 모델 엔드포인트에 POST 요청을 전송합니다.

MODEL_ID="gemini-2.5-flash"
PROJECT_ID="my-project"
TEXT="Provide a summary with about two sentences for the following article."
REGION="us-central1"

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:countTokens -d \
$'{
    "contents": [{
      "role": "user",
      "parts": [
        {
          "file_data": {
            "file_uri": "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
            "mime_type": "video/mp4"
          }
        },
        {
          "text": "'"$TEXT"'"
        }]
    }]
 }'

가격 책정 및 할당량

CountTokens API 사용에는 요금 또는 할당량 제한이 없습니다. CountTokens API의 최대 할당량은 분당 요청 3,000개입니다.

다음 단계