टोकन को समझें और उनकी गिनती करें

Gemini और जनरेटिव एआई के अन्य मॉडल, इनपुट और आउटपुट को टोकन नाम की ग्रैन्युलैरिटी पर प्रोसेस करते हैं.

Gemini के मॉडल के लिए, एक टोकन करीब-करीब चार वर्णों के बराबर होता है. 100 टोकन, अंग्रेज़ी के करीब 60 से 80 शब्दों के बराबर होते हैं.

टोकन के बारे में जानकारी

टोकन, z जैसे सिंगल वर्ण या cat जैसे पूरे शब्द हो सकते हैं. लंबे शब्दों को कई टोकन में बांटा जाता है. मॉडल के इस्तेमाल किए जाने वाले सभी टोकन के सेट को शब्दावली कहा जाता है. साथ ही, टेक्स्ट को टोकन में बांटने की प्रोसेस को टोकनाइज़ेशन कहा जाता है.

बिलिंग की सुविधा चालू होने पर, Gemini API को कॉल करने की लागत इनपुट और आउटपुट टोकन की संख्या के हिसाब से तय होती है. इसलिए, टोकन की गिनती करने का तरीका जानना मददगार साबित हो सकता है.

टोकन की गिनती करना

Gemini API के सभी इनपुट और आउटपुट को टोकनाइज़ किया जाता है. इनमें टेक्स्ट, इमेज फ़ाइलें, और टेक्स्ट के अलावा अन्य फ़ॉर्मैट शामिल हैं.

टोकन की गिनती इन तरीकों से की जा सकती है:

  • अनुरोध के इनपुट के साथ count_tokens को कॉल करें. यह फ़ंक्शन, सिर्फ़ इनपुट में मौजूद टोकन की कुल संख्या दिखाता है. अनुरोधों का साइज़ देखने के लिए, इनपुट भेजने से पहले इस फ़ंक्शन को कॉल करें.

  • इंटरैक्शन के जवाब में, usage का इस्तेमाल करें. यह फ़ंक्शन, इनपुट (total_input_tokens), आउटपुट (total_output_tokens), थिंकिंग (total_thought_tokens), कैश मेमोरी में सेव किए गए कॉन्टेंट (total_cached_tokens), टूल के इस्तेमाल (total_tool_use_tokens), और कुल (total_tokens) के लिए टोकन की संख्या दिखाता है.

टेक्स्ट टोकन की गिनती करना

Python

# This will only work for SDK newer than 2.0.0
from google import genai

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

# Count tokens before sending
total_tokens = client.models.count_tokens(
    model="gemini-3.8-flash",
    contents=prompt
)
print("total_tokens:", total_tokens.total_tokens)

# Get usage from interaction
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=prompt
)
print(interaction.usage)

JavaScript

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

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

// Count tokens before sending
const countResponse = await client.models.countTokens({
    model: "gemini-3.8-flash",
    contents: prompt,
});
console.log(countResponse.totalTokens);

// Get usage from interaction
const interaction = await client.interactions.create({
    model: "gemini-3.8-flash",
    input: prompt,
});
console.log(interaction.usage);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.CountTokensResponse;

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

// Count tokens before sending
CountTokensResponse countResponse =
    client.models.countTokens("gemini-3.8-flash", prompt, null);
System.out.println("total_tokens: " + countResponse.totalTokens().orElse(0));

// Get usage from interaction
CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of(prompt))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.usage().orElse(null));

REST

# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:countTokens" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"parts": [{"text": "The quick brown fox."}]}]}'

सिलसिलेवार बातचीत के टोकन की गिनती करना

previous_interaction_id का इस्तेमाल करके, बातचीत के इतिहास में मौजूद टोकन की गिनती करना:

Python

# This will only work for SDK newer than 2.0.0
# First interaction
interaction1 = client.interactions.create(
    model="gemini-3.8-flash",
    input="Hi, my name is Bob"
)

# Second interaction continues the conversation
interaction2 = client.interactions.create(
    model="gemini-3.8-flash",
    input="What's my name?",
    previous_interaction_id=interaction1.id
)

# Usage includes tokens from both turns
print(f"Input tokens: {interaction2.usage.total_input_tokens}")
print(f"Output tokens: {interaction2.usage.total_output_tokens}")
print(f"Total tokens: {interaction2.usage.total_tokens}")

JavaScript

// This will only work for SDK newer than 2.0.0
// First interaction
const interaction1 = await client.interactions.create({
    model: "gemini-3.8-flash",
    input: "Hi, my name is Bob"
});

// Second interaction continues the conversation
const interaction2 = await client.interactions.create({
    model: "gemini-3.8-flash",
    input: "What's my name?",
    previous_interaction_id: interaction1.id
});

console.log(`Input tokens: ${interaction2.usage.total_input_tokens}`);
console.log(`Output tokens: ${interaction2.usage.total_output_tokens}`);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Usage;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

// First interaction
CreateModelInteraction params1 =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Hi, my name is Bob"))
        .build();

Interaction interaction1 =
    client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();

// Second interaction continues the conversation
CreateModelInteraction params2 =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("What's my name?"))
        .previousInteractionId(interaction1.id().orElse(""))
        .build();

Interaction interaction2 =
    client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();

// Usage includes tokens from both turns
if (interaction2.usage().isPresent()) {
  Usage usage = interaction2.usage().get();
  System.out.println("Input tokens: " + usage.totalInputTokens().orElse(0));
  System.out.println("Output tokens: " + usage.totalOutputTokens().orElse(0));
  System.out.println("Total tokens: " + usage.totalTokens().orElse(0));
}

टेक्स्ट, इमेज, और वीडियो वगैरह को प्रोसेस करने वाले मोडल के टोकन की गिनती करना

Gemini API के सभी इनपुट को टोकनाइज़ किया जाता है. इनमें इमेज, वीडियो, और ऑडियो शामिल हैं. टोकनाइज़ेशन के बारे में अहम बातें:

  • इमेज: दोनों डाइमेंशन में ≤384 पिक्सल वाली इमेज को 258 टोकन के तौर पर गिना जाता है. बड़ी इमेज को 768x768 पिक्सल के टाइल में बांटा जाता है. हर टाइल को 258 टोकन के तौर पर गिना जाता है.
  • वीडियो: हर सेकंड के लिए 263 टोकन (यह सुविधा, स्टैटिक प्रोसेसिंग पर लागू होती है). एजेंटिक प्रोसेसिंग के लिए, टोकन का इस्तेमाल अलग-अलग होता है. प्रोसेसिंग मोड के हिसाब से, वीडियो के लिए टोकन के इस्तेमाल की जानकारी देखें .
  • ऑडियो: हर सेकंड के लिए 32 टोकन

इमेज टोकन

Python

# This will only work for SDK newer than 2.0.0
uploaded_file = client.files.upload(file="path/to/image.jpg")

# Count tokens for image + text
total_tokens = client.models.count_tokens(
    model="gemini-3.8-flash",
    contents=["Tell me about this image", uploaded_file]
)
print(f"Total tokens: {total_tokens}")

# Generate with image
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": "Tell me about this image"},
        {"type": "image", "uri": uploaded_file.uri, "mime_type": uploaded_file.mime_type}
    ]
)
print(interaction.usage)

JavaScript

// This will only work for SDK newer than 2.0.0
const uploadedFile = await client.files.upload({
    file: "path/to/image.jpg",
    config: { mimeType: "image/jpeg" }
});

// Count tokens
const countResponse = await client.models.countTokens({
    model: "gemini-3.8-flash",
    contents: [
        { text: "Tell me about this image" },
        { fileData: { fileUri: uploadedFile.uri, mimeType: uploadedFile.mimeType } }
    ]
});
console.log(countResponse.totalTokens);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.Content;
import com.google.genai.types.CountTokensResponse;
import com.google.genai.types.File;
import com.google.genai.types.Part;
import com.google.genai.types.UploadFileConfig;
import java.util.Arrays;

Client client = new Client();

File uploadedFile =
    client.files.upload(
        new java.io.File("path/to/image.jpg"),
        UploadFileConfig.builder().mimeType("image/jpeg").build());

// Count tokens for image + text
CountTokensResponse countResponse =
    client.models.countTokens(
        "gemini-3.8-flash",
        Arrays.asList(
            Content.fromParts(
                Part.fromText("Tell me about this image"),
                Part.fromUri(
                    uploadedFile.uri().orElse(""), uploadedFile.mimeType().orElse("image/jpeg")))),
        null);
System.out.println("Total tokens: " + countResponse.totalTokens().orElse(0));

// Generate with image
CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(
            InteractionsInput.ofContent(
                Arrays.asList(
                    TextContent.builder().text("Tell me about this image").build(),
                    ImageContent.builder()
                        .uri(uploadedFile.uri().orElse(""))
                        .mimeType(
                            ImageContentMimeType.of(uploadedFile.mimeType().orElse("image/jpeg")))
                        .build())))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.usage().orElse(null));

इनलाइन डेटा का उदाहरण:

Python

# This will only work for SDK newer than 2.0.0
import base64

with open('image.jpg', 'rb') as f:
    image_bytes = f.read()

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": "Describe this image"},
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/jpeg"
        }
    ]
)
print(interaction.usage)

वीडियो टोकन

Python

# This will only work for SDK newer than 2.0.0
import time

video_file = client.files.upload(file="path/to/video.mp4")

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

# A 60-second video is approximately 100 * 60 = 6,000 tokens
total_tokens = client.models.count_tokens(
    model="gemini-3.8-flash",
    contents=["Summarize this video", video_file]
)
print(f"Total tokens: {total_tokens}")

# Generate with video
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": "Summarize this video"},
        {"type": "video", "uri": video_file.uri, "mime_type": video_file.mime_type}
    ]
)
print(interaction.usage)

प्रोसेसिंग मोड के हिसाब से, वीडियो के लिए टोकन के इस्तेमाल की जानकारी

वीडियो के लिए टोकन का इस्तेमाल, प्रोसेसिंग मोड पर निर्भर करता है:

प्रोसेसिंग मोड टोकन की गिनती आम तौर पर इस्तेमाल
स्टैटिक (डिफ़ॉल्ट) डिफ़ॉल्ट रूप से, हर सेकंड के लिए ~100 टोकन (लो रिज़ॉल्यूशन) या हर सेकंड के लिए ~300 टोकन (हाई रिज़ॉल्यूशन). हर फ़्रेम को 1 FPS पर सैंपल किया जाता है. वीडियो की अवधि के हिसाब से, टोकन के इस्तेमाल का अनुमान लगाया जा सकता है.
एजेंटिक कॉन्टेंट की जटिलता के हिसाब से, टोकन के इस्तेमाल में अंतर होता है. मॉडल, प्रॉम्प्ट का जवाब देने के लिए सिर्फ़ ट्रांसक्रिप्ट और/या फ़्रेम और/या ऑडियो लोड करता है. लंबी अवधि वाले वीडियो के लिए, 88% तक कम टोकन का इस्तेमाल.

एजेंटिक प्रोसेसिंग के साथ, एक घंटे के लेक्चर के लिए स्टैटिक मोड में ~10.8 लाख टोकन का इस्तेमाल हो सकता है. वहीं, प्रॉम्प्ट और कॉन्टेंट के हिसाब से, ~1.08 लाख टोकन का इस्तेमाल हो सकता है.

किसी अनुरोध के लिए, टोकन के असल इस्तेमाल की जानकारी देखने के लिए, interaction.usage की जांच करें. एजेंटिक वीडियो टोकन की जानकारी, इन फ़ील्ड में दिखती है:

  • शुरुआती प्रॉम्प्ट (वीडियो रेफ़रंस + उपयोगकर्ता का प्रॉम्प्ट): total_input_tokens
  • नेविगेशन थिंकिंग: total_thought_tokens
  • मांग पर लोड की गई ट्रांसक्रिप्ट, फ़्रेम, और ऑडियो: total_tool_use_tokens
  • आखिरी जवाब: total_output_tokens

ऑडियो टोकन

Python

# This will only work for SDK newer than 2.0.0
audio_file = client.files.upload(file="path/to/audio.mp3")

# A 60-second audio clip is approximately 32 * 60 = 1,920 tokens
total_tokens = client.models.count_tokens(
    model="gemini-3.8-flash",
    contents=["Transcribe this audio", audio_file]
)
print(f"Total tokens: {total_tokens}")

# Generate with audio
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": "Transcribe this audio"},
        {"type": "audio", "uri": audio_file.uri, "mime_type": audio_file.mime_type}
    ]
)
print(interaction.usage)

सिस्टम के निर्देशों के टोकन की गिनती करना

सिस्टम के निर्देशों को, इनपुट टोकन के तौर पर गिना जाता है:

Python

# This will only work for SDK newer than 2.0.0
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Hello!",
    system_instruction="You are a helpful assistant who speaks like a pirate."
)

# system_instruction tokens included in total_input_tokens
print(f"Input tokens: {interaction.usage.total_input_tokens}")

टूल के टोकन की गिनती करना

टूल (फ़ंक्शन, कोड एक्ज़ीक्यूशन, Google Search) को भी गिना जाता है:

Python

# This will only work for SDK newer than 2.0.0
tools = [
    {
        "type": "function",
        "name": "get_weather",
        "description": "Get current weather",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            }
        }
    }
]

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="What's the weather in Tokyo?",
    tools=tools
)

print(f"Input tokens: {interaction.usage.total_input_tokens}")
print(f"Tool use tokens: {interaction.usage.total_tool_use_tokens}")

कॉन्टेक्स्ट विंडो

हर Gemini मॉडल के लिए, टोकन की एक तय संख्या होती है. कॉन्टेक्स्ट विंडो, इनपुट और आउटपुट टोकन की कुल सीमा तय करती है.

प्रोग्राम के ज़रिए, कॉन्टेक्स्ट विंडो का साइज़ पाना

Python

# This will only work for SDK newer than 2.0.0
model_info = client.models.get(model="gemini-3.8-flash")
print(f"Input token limit: {model_info.input_token_limit}")
print(f"Output token limit: {model_info.output_token_limit}")

JavaScript

// This will only work for SDK newer than 2.0.0
const modelInfo = await client.models.get({ model: "gemini-3.8-flash" });
console.log(`Input token limit: ${modelInfo.inputTokenLimit}`);
console.log(`Output token limit: ${modelInfo.outputTokenLimit}`);

Java

import com.google.genai.Client;
import com.google.genai.types.Model;

Client client = new Client();

Model modelInfo = client.models.get("gemini-3.8-flash", null);
System.out.println("Input token limit: " + modelInfo.inputTokenLimit().orElse(0));
System.out.println("Output token limit: " + modelInfo.outputTokenLimit().orElse(0));

मॉडल वाले पेज पर, कॉन्टेक्स्ट विंडो के साइज़ देखें.

आगे क्या करना है