שימוש ב-Count Tokens API

בדף הזה מוסבר איך לקבל את מספר האסימונים של הנחיה באמצעות countTokens API.

מודלים נתמכים

המודלים המולטי-מודאליים הבאים תומכים בקבלת אומדן של מספר הטוקנים בהנחיה:

לחצו כדי להרחיב את רשימת המודלים הנתמכים

מידע נוסף על גרסאות של מודלים זמין במאמר גרסאות ומחזור החיים של מודל Gemini.

קבלת מספר הטוקנים של הנחיה

אתם יכולים לקבל אומדן של מספר הטוקנים בהנחיה באמצעות Agent Platform API.

המסוף

כדי לספור את הטוקנים בהנחיה באמצעות Agent Studio ב-Gemini Enterprise Agent Platform במסוףGoogle Cloud :

  1. בקטע Agent Platform במסוף Google Cloud , נכנסים לדף Agent Studio.

    כניסה ל-Agent Studio

  2. לוחצים על פתיחת Freeform או על פתיחת Chat.
  3. מספר האסימונים מחושב ומוצג בזמן שמקלידים בחלונית Prompt. הוא כולל את מספר הטוקנים בכל קובצי הקלט.
  4. כדי לראות פרטים נוספים, לוחצים על <count> אסימונים כדי לפתוח את הכלי לניתוח אסימונים של הנחיות.
    • כדי לראות את הטוקנים בפרומפט הטקסטואלי שמודגשים בצבעים שונים שמסמנים את הגבול של כל מזהה טוקן, לוחצים על מזהה טוקן לטקסט. אין תמיכה בטוקנים של מדיה.
    • כדי לראות את מזהי האסימונים, לוחצים על מזהה אסימון.

      כדי לסגור את חלונית כלי הטוקניזציה, לוחצים על X או מחוץ לחלונית.

Python

התקנה

pip install --upgrade google-genai

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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-3.8-flash",
    contents="What's the highest mountain in Africa?",
)
print(response)
# Example output:
# total_tokens=9
# cached_content_token_count=None

Go

איך מתקינים או מעדכנים את Go

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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 client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

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

  console.log(response);

  return response.totalTokens;
}

Java

איך מתקינים או מעדכנים את Java

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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

כדי לקבל את מספר האסימונים של הנחיה באמצעות Agent Platform API, שולחים בקשת POST לנקודת הקצה של המודל של בעל התוכן הדיגיטלי.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫LOCATION: האזור שבו הבקשה תעובד. האפשרויות הזמינות כוללות:

    רשימה חלקית של האזורים הזמינים

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • ‫PROJECT_ID: מזהה הפרויקט.
  • ‫MODEL_ID: מזהה המודל של המודל המולטי-מודאלי שבו רוצים להשתמש.
  • ROLE: התפקיד בשיחה שמשויך לתוכן. חובה לציין תפקיד גם בתרחישי שימוש של פנייה אחת. הערכים הקבילים כוללים:
    • USER: מציין תוכן שאתם שלחתם.
  • TEXT: ההוראות בטקסט שצריך לכלול בהנחיה.

ה-method של ה-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.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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-3.5-flash",
    contents=contents,
)
print(response)
# Example output:
# total_tokens=16252 cached_content_token_count=None

Go

איך מתקינים או מעדכנים את Go

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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: genai.RoleUser},
	}

	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.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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 client = 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 client.models.countTokens({
    model: 'gemini-2.5-flash',
    contents: [video, 'Provide a description of the video.'],
  });

  console.log(response);

  return response.totalTokens;
}

Java

איך מתקינים או מעדכנים את Java

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# 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_ENTERPRISE=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

כדי לקבל את מספר האסימונים של הנחיה באמצעות Agent Platform API, שולחים בקשת POST לנקודת הקצה של המודל של בעל התוכן הדיגיטלי.

MODEL_ID="gemini-3.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"'"
        }]
    }]
 }'

תמחור ומכסות

אין חיוב או הגבלת מכסה על השימוש ב-API של CountTokens. המכסה המקסימלית ל-API של CountTokens היא 3,000 בקשות לדקה.

המאמרים הבאים