CountTokens API

CountTokens API는 요청을 Gemini API에 전송하기 전에 입력 토큰 수를 계산합니다.

CountTokens API를 사용하면 요청이 모델 컨텍스트 윈도우를 초과하지 않게 하고 청구 가능한 문자를 기준으로 잠재 비용을 예측할 수 있습니다.

CountTokens API는 Gemini API 추론 요청과 동일한 contents 파라미터를 사용할 수 있습니다.

지원되는 모델:

모델 코드
Gemini 1.5 Flash gemini-1.5-flash-002
gemini-1.5-flash-001
gemini-1.5-flash-preview-0514
Gemini 1.5 Pro gemini-1.5-pro-002
gemini-1.5-pro-001
gemini-1.5-pro-preview-0514
Gemini 1.0 Pro Vision gemini-1.0-pro-vision
gemini-1.0-pro-vision-001
Gemini 1.0 Pro gemini-1.0-pro
gemini-1.0-pro-001
gemini-1.0-pro-002
Gemini Experimental gemini-experimental

제한사항:

gemini-1.0-pro-vision-001gemini-1.0-ultra-vision-001은 동영상 입력에 고정된 토큰 수를 사용합니다.

예시 문법

집계 토큰 요청을 전송하는 구문입니다.

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \

https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:countTokens \
-d '{
  "contents": [{
    ...
  }],
  "system_instruction": {
  "role": "...",
  "parts": [{
      ...
    }],
  "tools": [{
      "function_declarations": [{
        ...
      }]
    }],
  }
}'

Python

gemini_model = GenerativeModel(MODEL_ID)
model_response = gemini_model.count_tokens([...])

매개변수 목록

이 클래스는 roleparts라는 두 가지 기본 속성으로 구성됩니다. role 속성은 콘텐츠를 생성하는 개별 사용자를 나타내고 parts 속성에는 여러 요소가 포함되며 각 요소는 메시지 내 데이터 세그먼트를 나타냅니다.

매개변수

role

선택사항: string

메시지를 만드는 항목의 ID입니다. 문자열을 다음 중 하나로 설정합니다.

  • user: 실제 사람이 메시지를 보냈음을 나타냅니다. 예를 들어 사용자가 생성한 메시지입니다.
  • model: 메시지가 모델에서 생성되었음을 나타냅니다.

model 값은 멀티턴 대화 중에 모델의 메시지를 대화에 삽입하는 데 사용됩니다.

멀티턴이 아닌 대화의 경우 이 필드를 비워 두거나 설정하지 않을 수 있습니다.

parts

part

단일 메시지를 구성하는 순서가 지정된 부분의 목록입니다. 부분마다 IANA MIME 유형이 다를 수 있습니다.

Part

멀티 파트 Content 메시지의 일부인 미디어를 포함하는 데이터 유형입니다.

매개변수

text

선택사항: string

텍스트 프롬프트 또는 코드 스니펫입니다.

inline_data

선택사항: Blob

원시 바이트의 인라인 데이터입니다.

file_data

(선택사항) FileData

파일에 저장된 데이터입니다.

Blob

콘텐츠 blob. 가능하다면 원시 바이트가 아닌 텍스트로 보냅니다.

매개변수

mime_type

string

데이터의 IANA MIME 유형입니다.

data

bytes

원시 바이트입니다.

FileData

URI 기반 데이터.

매개변수

mime_type

string

데이터의 IANA MIME 유형입니다.

file_uri

string

데이터를 저장하는 파일에 대한 Cloud Storage URI입니다.

system_instruction

이 필드는 사용자가 제공한 system_instructions용입니다. contents와 동일하지만 콘텐츠 유형에 대한 지원이 제한됩니다.

매개변수

role

string

데이터의 IANA MIME 유형입니다. 이 필드는 내부적으로 무시됩니다.

parts

Part

텍스트 전용. 사용자가 모델에 전달하려는 안내입니다.

FunctionDeclaration

모델에서 JSON 입력을 생성할 수 있는 함수를 나타내는 OpenAPI 3.0 사양에서 정의된 함수 선언의 구조화된 표현입니다.

매개변수

name

string

호출하려는 함수의 이름입니다.

description

(선택사항) string

함수 설명 및 용도입니다.

parameters

(선택사항) Schema

함수 파라미터를 OpenAPI JSON 스키마 객체 형식인 OpenAPI 3.0 사양으로 설명합니다.

response

(선택사항) Schema

함수의 출력을 OpenAPI JSON 스키마 객체 형식인 OpenAPI 3.0 사양으로 설명합니다.

예시

텍스트 프롬프트에서 토큰 수 가져오기

이 예시에서는 단일 텍스트 프롬프트의 토큰을 집계합니다.

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

import vertexai
from vertexai.generative_models import GenerativeModel

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel("gemini-1.5-flash-002")

prompt = "Why is the sky blue?"
# Prompt tokens count
response = model.count_tokens(prompt)
print(f"Prompt Token Count: {response.total_tokens}")
print(f"Prompt Character Count: {response.total_billable_characters}")

# Send text to Gemini
response = model.generate_content(prompt)

# Response tokens count
usage_metadata = response.usage_metadata
print(f"Prompt Token Count: {usage_metadata.prompt_token_count}")
print(f"Candidates Token Count: {usage_metadata.candidates_token_count}")
print(f"Total Token Count: {usage_metadata.total_token_count}")
# Example response:
# Prompt Token Count: 6
# Prompt Character Count: 16
# Prompt Token Count: 6
# Candidates Token Count: 315
# Total Token Count: 321

NodeJS

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function countTokens(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const req = {
    contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
  };

  // Prompt tokens count
  const countTokensResp = await generativeModel.countTokens(req);
  console.log('Prompt tokens count: ', countTokensResp);

  // Send text to gemini
  const result = await generativeModel.generateContent(req);

  // Response tokens count
  const usageMetadata = result.response.usageMetadata;
  console.log('Response tokens count: ', usageMetadata);
}

Java

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.CountTokensResponse;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import java.io.IOException;

public class GetTokenCount {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.5-flash-001";

    getTokenCount(projectId, location, modelName);
  }

  // Gets the number of tokens for the prompt and the model's response.
  public static int getTokenCount(String projectId, String location, String modelName)
      throws IOException {
    // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) {
      GenerativeModel model = new GenerativeModel(modelName, vertexAI);

      String textPrompt = "Why is the sky blue?";
      CountTokensResponse response = model.countTokens(textPrompt);

      int promptTokenCount = response.getTotalTokens();
      int promptCharCount = response.getTotalBillableCharacters();

      System.out.println("Prompt token Count: " + promptTokenCount);
      System.out.println("Prompt billable character count: " + promptCharCount);

      GenerateContentResponse contentResponse = model.generateContent(textPrompt);

      int tokenCount = contentResponse.getUsageMetadata().getPromptTokenCount();
      int candidateTokenCount = contentResponse.getUsageMetadata().getCandidatesTokenCount();
      int totalTokenCount = contentResponse.getUsageMetadata().getTotalTokenCount();

      System.out.println("Prompt token Count: " + tokenCount);
      System.out.println("Candidate Token Count: " + candidateTokenCount);
      System.out.println("Total token Count: " + totalTokenCount);

      return promptTokenCount;
    }
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// countTokens returns the number of tokens for this prompt.
func countTokens(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-flash-001"

	ctx := context.Background()
	prompt := genai.Text("Why is the sky blue?")

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	resp, err := model.CountTokens(ctx, prompt)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Number of tokens for the prompt: %d\n", resp.TotalTokens)

	resp2, err := model.GenerateContent(ctx, prompt)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Number of tokens for the prompt: %d\n", resp2.UsageMetadata.PromptTokenCount)
	fmt.Fprintf(w, "Number of tokens for the candidates: %d\n", resp2.UsageMetadata.CandidatesTokenCount)
	fmt.Fprintf(w, "Total number of tokens: %d\n", resp2.UsageMetadata.TotalTokenCount)

	return nil
}

미디어 프롬프트에서 토큰 수 가져오기

이 예시에서는 다양한 미디어 유형을 사용하는 프롬프트의 토큰을 집계합니다.

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: 프롬프트에 포함할 텍스트 안내입니다.
  • FILE_URI: 프롬프트에 포함할 파일의 URI 또는 URL입니다. 허용되는 값은 다음과 같습니다.
    • Cloud Storage 버킷 URI: 객체는 공개적으로 읽을 수 있거나 요청을 보내는 동일한 Google Cloud 프로젝트에 있어야 합니다. gemini-1.5-progemini-1.5-flash의 경우 크기 제한은 2GB입니다. gemini-1.0-pro-vision의 경우 크기 제한은 20MB입니다.
    • HTTP URL: 파일 URL은 공개적으로 읽을 수 있어야 합니다. 요청당 하나의 동영상 파일, 하나의 오디오 파일, 최대 10개의 이미지 파일을 지정할 수 있습니다. 오디오 파일, 동영상 파일, 문서는 15MB를 초과할 수 없습니다.
    • YouTube 동영상 URL: YouTube 동영상은 Google Cloud 콘솔에 로그인하는 데 사용된 계정이 소유한 것이거나 공개된 동영상이어야 합니다. 요청당 하나의 YouTube 동영상 URL만 지원됩니다.

    fileURI를 지정할 때는 파일의 미디어 유형(mimeType)도 지정해야 합니다. VPC 서비스 제어가 사용 설정된 경우 fileURI의 미디어 파일 URL을 지정하는 것은 지원되지 않습니다.

  • MIME_TYPE: data 또는 fileUri 필드에 지정된 파일의 미디어 유형입니다. 허용되는 값은 다음과 같습니다.

    클릭하여 MIME 유형 펼치기

    • application/pdf
    • audio/mpeg
    • audio/mp3
    • audio/wav
    • image/png
    • image/jpeg
    • image/webp
    • text/plain
    • video/mov
    • video/mpeg
    • video/mp4
    • video/mpg
    • video/avi
    • video/wmv
    • video/mpegps
    • video/flv

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": [
      {
        "file_data": {
          "file_uri": "FILE_URI",
          "mime_type": "MIME_TYPE"
        }
      },
      {
        "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

import vertexai
from vertexai.generative_models import GenerativeModel, Part

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel("gemini-1.5-flash-002")

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

# tokens count for user prompt
response = model.count_tokens(contents)
print(f"Prompt Token Count: {response.total_tokens}")
print(f"Prompt Character Count: {response.total_billable_characters}")
# Example response:
#     Prompt Token Count: 16822
#     Prompt Character Count: 30

# Send text to Gemini
response = model.generate_content(contents)
usage_metadata = response.usage_metadata

# tokens count for model response
print(f"Prompt Token Count: {usage_metadata.prompt_token_count}")
print(f"Candidates Token Count: {usage_metadata.candidates_token_count}")
print(f"Total Token Count: {usage_metadata.total_token_count}")
# Example response:
#     Prompt Token Count: 16822
#     Candidates Token Count: 71
#     Total Token Count: 16893

NodeJS

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function countTokens(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const req = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            file_data: {
              file_uri:
                'gs://cloud-samples-data/generative-ai/video/pixel8.mp4',
              mime_type: 'video/mp4',
            },
          },
          {text: 'Provide a description of the video.'},
        ],
      },
    ],
  };

  const countTokensResp = await generativeModel.countTokens(req);
  console.log('Prompt Token Count:', countTokensResp.totalTokens);
  console.log(
    'Prompt Character Count:',
    countTokensResp.totalBillableCharacters
  );

  // Sent text to Gemini
  const result = await generativeModel.generateContent(req);
  const usageMetadata = result.response.usageMetadata;

  console.log('Prompt Token Count:', usageMetadata.promptTokenCount);
  console.log('Candidates Token Count:', usageMetadata.candidatesTokenCount);
  console.log('Total Token Count:', usageMetadata.totalTokenCount);
}

Java

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.Content;
import com.google.cloud.vertexai.api.CountTokensResponse;
import com.google.cloud.vertexai.generativeai.ContentMaker;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.PartMaker;
import java.io.IOException;

public class GetMediaTokenCount {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.5-flash-001";

    getMediaTokenCount(projectId, location, modelName);
  }

  // Gets the number of tokens for the prompt with text and video and the model's response.
  public static int getMediaTokenCount(String projectId, String location, String modelName)
      throws IOException {
    // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) {
      GenerativeModel model = new GenerativeModel(modelName, vertexAI);

      Content content = ContentMaker.fromMultiModalData(
          "Provide a description of the video.",
          PartMaker.fromMimeTypeAndData(
              "video/mp4", "gs://cloud-samples-data/generative-ai/video/pixel8.mp4")
      );

      CountTokensResponse response = model.countTokens(content);

      int tokenCount = response.getTotalTokens();
      System.out.println("Token count: " + tokenCount);

      return tokenCount;
    }
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"mime"
	"path/filepath"

	"cloud.google.com/go/vertexai/genai"
)

// countTokensMultimodal finds the number of tokens for a multimodal prompt (video+text), and writes to w. Then,
// it calls the model with the multimodal prompt and writes token counts from the response metadata to w.
//
// video is a Google Cloud Storage path starting with "gs://"
func countTokensMultimodal(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-flash-001"
	prompt := "Provide a description of the video."
	video := "gs://cloud-samples-data/generative-ai/video/pixel8.mp4"

	ctx := context.Background()

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	part1 := genai.Text(prompt)

	// Given a video file URL, prepare video file as genai.Part
	part2 := genai.FileData{
		MIMEType: mime.TypeByExtension(filepath.Ext(video)),
		FileURI:  video,
	}

	// Finds the total number of tokens for the 2 parts (text, video) of the multimodal prompt,
	// before actually calling the model for inference.
	resp, err := model.CountTokens(ctx, part1, part2)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Number of tokens for the multimodal video prompt: %d\n", resp.TotalTokens)

	res, err := model.GenerateContent(ctx, part1, part2)
	if err != nil {
		return fmt.Errorf("unable to generate contents: %w", err)
	}

	// The token counts are also provided in the model response metadata, after inference.
	fmt.Fprintln(w, "\nModel response")
	md := res.UsageMetadata
	fmt.Fprintf(w, "Prompt Token Count: %d\n", md.PromptTokenCount)
	fmt.Fprintf(w, "Candidates Token Count: %d\n", md.CandidatesTokenCount)
	fmt.Fprintf(w, "Total Token Count: %d\n", md.TotalTokenCount)

	return nil
}

다음 단계