Понимать и считать жетоны


Gemini и другие генеративные модели ИИ обрабатывают ввод и вывод с степенью детализации, называемой токеном .

О токенах

Токенами могут быть отдельные символы, например z , или целые слова, например cat . Длинные слова разбиваются на несколько токенов. Набор всех токенов, используемых моделью, называется словарем, а процесс разделения текста на токены — токенизацией .

Для моделей Gemini токен эквивалентен примерно 4 символам. 100 токенов равны примерно 60-80 английским словам.

Если включено выставление счетов, стоимость вызова API Gemini частично определяется количеством входных и выходных токенов, поэтому знание того, как подсчитывать токены, может оказаться полезным.

Подсчитайте жетоны

Все входные и выходные данные Gemini API токенизированы, включая текст, файлы изображений и другие нетекстовые модальности.

Подсчитать жетоны можно следующими способами:

  • Вызов countTokens при вводе запроса.
    Это возвращает общее количество токенов только во входных данных . Вы можете сделать этот вызов перед отправкой входных данных в модель, чтобы проверить размер ваших запросов.

  • Используйте атрибут usageMetadata в объекте response после generate_content .
    Это возвращает общее количество токенов как на входе, так и на выходе : totalTokenCount .
    Он также возвращает количество входных и выходных токенов отдельно: promptTokenCount (входные токены) и candidatesTokenCount (выходные токены).

Подсчет текстовых жетонов

Если вы вызываете countTokens с текстовым вводом, он возвращает количество токенов только для текста на входе ( totalTokens ). Вы можете сделать этот вызов перед вызовом generateContent , чтобы проверить размер ваших запросов.

Другой вариант — вызвать generateContent , а затем использовать атрибут usageMetadata объекта response , чтобы получить следующее:

  • Отдельные счетчики токенов на входе ( promptTokenCount ) и выходе ( candidatesTokenCount ).
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount ).
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "The quick brown fox jumps over the lazy dog.";
const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: prompt,
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: prompt,
});
console.log(generateResponse.usageMetadata);

Подсчет многоходовых (чатовых) жетонов

Если вы вызываете countTokens с историей чата, он возвращает общее количество токенов текста для каждой роли в чате ( totalTokens ).

Другой вариант — вызвать sendMessage , а затем использовать атрибут usageMetadata объекта response , чтобы получить следующее:

  • Отдельные счетчики токенов на входе ( promptTokenCount ) и выходе ( candidatesTokenCount ).
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount ).

Чтобы понять, насколько большим будет ваш следующий диалог, вам нужно добавить его в историю при вызове countTokens .

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// Initial chat history.
const history = [
  { role: "user", parts: [{ text: "Hi my name is Bob" }] },
  { role: "model", parts: [{ text: "Hi Bob!" }] },
];
const chat = ai.chats.create({
  model: "gemini-2.0-flash",
  history: history,
});

// Count tokens for the current chat history.
const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: chat.getHistory(),
});
console.log(countTokensResponse.totalTokens);

const chatResponse = await chat.sendMessage({
  message: "In one sentence, explain how a computer works to a young child.",
});
console.log(chatResponse.usageMetadata);

// Add an extra user message to the history.
const extraMessage = {
  role: "user",
  parts: [{ text: "What is the meaning of life?" }],
};
const combinedHistory = chat.getHistory();
combinedHistory.push(extraMessage);
const combinedCountTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: combinedHistory,
});
console.log(
  "Combined history token count:",
  combinedCountTokensResponse.totalTokens,
);

Подсчитайте мультимодальные токены

Все входные данные в Gemini API токенизированы, включая текст, файлы изображений и другие нетекстовые модальности. Обратите внимание на следующие ключевые моменты высокого уровня, касающиеся токенизации мультимодальных входных данных во время обработки Gemini API:

  • В Gemini 2.0 входные изображения с обоими размерами <= 384 пикселей считаются как 258 токенов. Изображения, увеличенные в одном или обоих измерениях, обрезаются и масштабируются по мере необходимости в плитки размером 768x768 пикселей, каждая из которых считается 258 токенами. До Gemini 2.0 изображения использовали фиксированные 258 токенов.

  • Видео- и аудиофайлы конвертируются в токены по следующим фиксированным скоростям: видео — 263 токена в секунду, аудио — 32 токена в секунду.

Файлы изображений

Если вы вызываете countTokens с вводом текста и изображения, он возвращает объединенное количество токенов текста и изображения только на входе ( totalTokens ). Вы можете сделать этот вызов перед вызовом generateContent , чтобы проверить размер ваших запросов. Вы также можете дополнительно вызвать countTokens для текста и файла отдельно.

Другой вариант — вызвать generateContent , а затем использовать атрибут usageMetadata объекта response , чтобы получить следующее:

  • Отдельные счетчики токенов на входе ( promptTokenCount ) и выходе ( candidatesTokenCount ).
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount ).

Пример использования загруженного изображения из File API:

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this image";
const organ = await ai.files.upload({
  file: path.join(media, "organ.jpg"),
  config: { mimeType: "image/jpeg" },
});

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(organ.uri, organ.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(organ.uri, organ.mimeType),
  ]),
});
console.log(generateResponse.usageMetadata);

Пример, предоставляющий изображение как встроенные данные:

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this image";
const imageBuffer = fs.readFileSync(path.join(media, "organ.jpg"));

// Convert buffer to base64 string.
const imageBase64 = imageBuffer.toString("base64");

// Build contents using createUserContent and createPartFromBase64.
const contents = createUserContent([
  prompt,
  createPartFromBase64(imageBase64, "image/jpeg"),
]);

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(generateResponse.usageMetadata);

Видео или аудио файлы

Аудио и видео конвертируются в токены по следующим фиксированным ставкам:

  • Видео: 263 токена в секунду
  • Аудио: 32 токена в секунду

Если вы вызываете countTokens с вводом текста и видео/аудио, он возвращает объединенное количество токенов текста и видео/аудиофайла только на входе ( totalTokens ). Вы можете сделать этот вызов перед вызовом generateContent , чтобы проверить размер ваших запросов. Вы также можете дополнительно вызвать countTokens для текста и файла отдельно.

Другой вариант — вызвать generateContent , а затем использовать атрибут usageMetadata объекта response , чтобы получить следующее:

  • Отдельные счетчики токенов на входе ( promptTokenCount ) и выходе ( candidatesTokenCount ).
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount ).
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this video";
let videoFile = await ai.files.upload({
  file: path.join(media, "Big_Buck_Bunny.mp4"),
  config: { mimeType: "video/mp4" },
});

// Poll until the video file is completely processed (state becomes ACTIVE).
while (!videoFile.state || videoFile.state.toString() !== "ACTIVE") {
  console.log("Processing video...");
  console.log("File state: ", videoFile.state);
  await sleep(5000);
  videoFile = await ai.files.get({ name: videoFile.name });
}

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(videoFile.uri, videoFile.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(videoFile.uri, videoFile.mimeType),
  ]),
});
console.log(generateResponse.usageMetadata);

Системные инструкции и инструменты

Системные инструкции и инструменты также учитываются при подсчете общего количества токенов для ввода.

Если вы используете системные инструкции, количество totalTokens увеличивается, отражая добавление systemInstruction .

Если вы используете вызов функций, количество totalTokens увеличивается, отражая добавление tools .

,


Близнецы и другие генеративные модели ИИ обрабатывают вход и выход в гранулярности, называемом токеном .

О токенах

Токены могут быть отдельными символами, такими как z или целые слова, как cat . Длинные слова разбиты на несколько жетонов. Набор всех токенов, используемых моделью, называется словарем, а процесс разделения текста на токены называют токенами .

Для моделей Близнецов токен эквивалентен примерно 4 символам. 100 токенов равны около 60-80 английских слов.

Когда выставление счета включено, стоимость вызова API Близнецов частично определяется количеством входных и выходных токенов, поэтому знание того, как считать токены, может быть полезным.

Считайте токены

Все входные данные и вывод от API Gemini токенизированы, включая текст, файлы изображений и другие нетекстовые методы.

Вы можете сосчитать токены следующими способами:

  • Вызовы countTokens с вводом запроса.
    Это возвращает общее количество токенов только на входе . Вы можете сделать этот вызов перед отправкой ввода в модель, чтобы проверить размер ваших запросов.

  • Используйте атрибут usageMetadata на объекте response после вызова generate_content .
    Это возвращает общее количество токенов как при входе, так и на выходе : totalTokenCount .
    Он также возвращает количество токенов ввода и вывода отдельно: promptTokenCount (входные токены) и candidatesTokenCount (выходные токены).

Считайте текстовые токены

Если вы звоните countTokens с входом только для текста, он возвращает количество токенов текста только на входе ( totalTokens ). Вы можете сделать этот звонок перед вызовом generateContent , чтобы проверить размер ваших запросов.

Другой вариант - это вызов generateContent , а затем использование атрибута usageMetadata в объекте response , чтобы получить следующее:

  • Отдельное количество токенов ввода ( promptTokenCount ) и вывода ( candidatesTokenCount )
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount )
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "The quick brown fox jumps over the lazy dog.";
const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: prompt,
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: prompt,
});
console.log(generateResponse.usageMetadata);

Считайте токены многообразования (чат)

Если вы звоните countTokens с историей чата, он возвращает общее количество токенов текста из каждой роли в чате ( totalTokens ).

Другой вариант - вызов sendMessage , а затем использование атрибута usageMetadata в объекте response , чтобы получить следующее:

  • Отдельное количество токенов ввода ( promptTokenCount ) и вывода ( candidatesTokenCount )
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount )

Чтобы понять, насколько большим будет ваш следующий разговорный поворот, вам нужно добавить его в историю, когда вы звоните countTokens .

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// Initial chat history.
const history = [
  { role: "user", parts: [{ text: "Hi my name is Bob" }] },
  { role: "model", parts: [{ text: "Hi Bob!" }] },
];
const chat = ai.chats.create({
  model: "gemini-2.0-flash",
  history: history,
});

// Count tokens for the current chat history.
const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: chat.getHistory(),
});
console.log(countTokensResponse.totalTokens);

const chatResponse = await chat.sendMessage({
  message: "In one sentence, explain how a computer works to a young child.",
});
console.log(chatResponse.usageMetadata);

// Add an extra user message to the history.
const extraMessage = {
  role: "user",
  parts: [{ text: "What is the meaning of life?" }],
};
const combinedHistory = chat.getHistory();
combinedHistory.push(extraMessage);
const combinedCountTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: combinedHistory,
});
console.log(
  "Combined history token count:",
  combinedCountTokensResponse.totalTokens,
);

Считайте мультимодальные жетоны

Все входные данные в API Близнецы являются токенизированы, включая текст, файлы изображений и другие нетекстовые модальности. Обратите внимание на следующие ключевые моменты высокого уровня о токенизации мультимодального ввода во время обработки с помощью API Gemini:

  • С Gemini 2.0 входы изображений с обоими измерениями <= 384 пикселей считаются 258 токенами. Изображения больше в одном или обоих размерах обрезаны и масштабируются по мере необходимости в плитки 768x768 пикселей, каждый из которых считается 258 токенами. До Gemini 2.0 изображения использовали фиксированные 258 токенов.

  • Видео и аудиофайлы преобразуются в токены по следующим фиксированным тарифам: видео по 263 токенам в секунду и аудио по 32 токенам в секунду.

Файлы изображений

Если вы звоните countTokens с вводом текста и изображения, он возвращает комбинированное количество токенов текста и изображение только на вводе ( totalTokens ). Вы можете сделать этот звонок перед вызовом generateContent , чтобы проверить размер ваших запросов. Вы также можете необязательно вызовать countTokens в тексте и файл отдельно.

Другой вариант - это вызов generateContent , а затем использование атрибута usageMetadata в объекте response , чтобы получить следующее:

  • Отдельное количество токенов ввода ( promptTokenCount ) и вывода ( candidatesTokenCount )
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount )

Пример, который использует загруженное изображение из API файла:

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this image";
const organ = await ai.files.upload({
  file: path.join(media, "organ.jpg"),
  config: { mimeType: "image/jpeg" },
});

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(organ.uri, organ.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(organ.uri, organ.mimeType),
  ]),
});
console.log(generateResponse.usageMetadata);

Пример, который предоставляет изображение как встроенные данные:

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this image";
const imageBuffer = fs.readFileSync(path.join(media, "organ.jpg"));

// Convert buffer to base64 string.
const imageBase64 = imageBuffer.toString("base64");

// Build contents using createUserContent and createPartFromBase64.
const contents = createUserContent([
  prompt,
  createPartFromBase64(imageBase64, "image/jpeg"),
]);

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(generateResponse.usageMetadata);

Видео или аудиофайлы

Аудио и видео преобразуются в токены по следующим фиксированным ставкам:

  • Видео: 263 токена в секунду
  • Аудио: 32 жетона в секунду

Если вы звоните countTokens с текстовым и видео/аудио входом, он возвращает комбинированное количество токенов текста и видео/аудиофайл только на вводе ( totalTokens ). Вы можете сделать этот звонок перед вызовом generateContent , чтобы проверить размер ваших запросов. Вы также можете необязательно вызовать countTokens в тексте и файл отдельно.

Другой вариант - это вызов generateContent , а затем использование атрибута usageMetadata в объекте response , чтобы получить следующее:

  • Отдельное количество токенов ввода ( promptTokenCount ) и вывода ( candidatesTokenCount )
  • Общее количество токенов как на входе, так и на выходе ( totalTokenCount )
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this video";
let videoFile = await ai.files.upload({
  file: path.join(media, "Big_Buck_Bunny.mp4"),
  config: { mimeType: "video/mp4" },
});

// Poll until the video file is completely processed (state becomes ACTIVE).
while (!videoFile.state || videoFile.state.toString() !== "ACTIVE") {
  console.log("Processing video...");
  console.log("File state: ", videoFile.state);
  await sleep(5000);
  videoFile = await ai.files.get({ name: videoFile.name });
}

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(videoFile.uri, videoFile.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(videoFile.uri, videoFile.mimeType),
  ]),
});
console.log(generateResponse.usageMetadata);

Системные инструкции и инструменты

Системные инструкции и инструменты также учитываются к общему количеству токенов для ввода.

Если вы используете системные инструкции, количество totalTokens увеличивается, чтобы отразить добавление systemInstruction .

Если вы используете вызовы функций, количество totalTokens увеличивается, чтобы отразить добавление tools .

,


Gemini and other generative AI models process input and output at a granularity called a token .

About tokens

Tokens can be single characters like z or whole words like cat . Long words are broken up into several tokens. The set of all tokens used by the model is called the vocabulary, and the process of splitting text into tokens is called tokenization .

For Gemini models, a token is equivalent to about 4 characters. 100 tokens is equal to about 60-80 English words.

When billing is enabled, the cost of a call to the Gemini API is determined in part by the number of input and output tokens, so knowing how to count tokens can be helpful.

Count tokens

All input to and output from the Gemini API is tokenized, including text, image files, and other non-text modalities.

You can count tokens in the following ways:

  • Call countTokens with the input of the request.
    This returns the total number of tokens in the input only . You can make this call before sending the input to the model to check the size of your requests.

  • Use the usageMetadata attribute on the response object after calling generate_content .
    This returns the total number of tokens in both the input and the output : totalTokenCount .
    It also returns the token counts of the input and output separately: promptTokenCount (input tokens) and candidatesTokenCount (output tokens).

Count text tokens

If you call countTokens with a text-only input, it returns the token count of the text in the input only ( totalTokens ). You can make this call before calling generateContent to check the size of your requests.

Another option is calling generateContent and then using the usageMetadata attribute on the response object to get the following:

  • The separate token counts of the input ( promptTokenCount ) and the output ( candidatesTokenCount )
  • The total number of tokens in both the input and the output ( totalTokenCount )
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "The quick brown fox jumps over the lazy dog.";
const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: prompt,
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: prompt,
});
console.log(generateResponse.usageMetadata);

Count multi-turn (chat) tokens

If you call countTokens with the chat history, it returns the total token count of the text from each role in the chat ( totalTokens ).

Another option is calling sendMessage and then using the usageMetadata attribute on the response object to get the following:

  • The separate token counts of the input ( promptTokenCount ) and the output ( candidatesTokenCount )
  • The total number of tokens in both the input and the output ( totalTokenCount )

To understand how big your next conversational turn will be, you need to append it to the history when you call countTokens .

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// Initial chat history.
const history = [
  { role: "user", parts: [{ text: "Hi my name is Bob" }] },
  { role: "model", parts: [{ text: "Hi Bob!" }] },
];
const chat = ai.chats.create({
  model: "gemini-2.0-flash",
  history: history,
});

// Count tokens for the current chat history.
const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: chat.getHistory(),
});
console.log(countTokensResponse.totalTokens);

const chatResponse = await chat.sendMessage({
  message: "In one sentence, explain how a computer works to a young child.",
});
console.log(chatResponse.usageMetadata);

// Add an extra user message to the history.
const extraMessage = {
  role: "user",
  parts: [{ text: "What is the meaning of life?" }],
};
const combinedHistory = chat.getHistory();
combinedHistory.push(extraMessage);
const combinedCountTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: combinedHistory,
});
console.log(
  "Combined history token count:",
  combinedCountTokensResponse.totalTokens,
);

Count multimodal tokens

All input to the Gemini API is tokenized, including text, image files, and other non-text modalities. Note the following high-level key points about tokenization of multimodal input during processing by the Gemini API:

  • With Gemini 2.0, image inputs with both dimensions <=384 pixels are counted as 258 tokens. Images larger in one or both dimensions are cropped and scaled as needed into tiles of 768x768 pixels, each counted as 258 tokens. Prior to Gemini 2.0, images used a fixed 258 tokens.

  • Video and audio files are converted to tokens at the following fixed rates: video at 263 tokens per second and audio at 32 tokens per second.

Image files

If you call countTokens with a text-and-image input, it returns the combined token count of the text and the image in the input only ( totalTokens ). You can make this call before calling generateContent to check the size of your requests. You can also optionally call countTokens on the text and the file separately.

Another option is calling generateContent and then using the usageMetadata attribute on the response object to get the following:

  • The separate token counts of the input ( promptTokenCount ) and the output ( candidatesTokenCount )
  • The total number of tokens in both the input and the output ( totalTokenCount )

Example that uses an uploaded image from the File API:

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this image";
const organ = await ai.files.upload({
  file: path.join(media, "organ.jpg"),
  config: { mimeType: "image/jpeg" },
});

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(organ.uri, organ.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(organ.uri, organ.mimeType),
  ]),
});
console.log(generateResponse.usageMetadata);

Example that provides the image as inline data:

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this image";
const imageBuffer = fs.readFileSync(path.join(media, "organ.jpg"));

// Convert buffer to base64 string.
const imageBase64 = imageBuffer.toString("base64");

// Build contents using createUserContent and createPartFromBase64.
const contents = createUserContent([
  prompt,
  createPartFromBase64(imageBase64, "image/jpeg"),
]);

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(generateResponse.usageMetadata);

Video or audio files

Audio and video are each converted to tokens at the following fixed rates:

  • Video: 263 tokens per second
  • Audio: 32 tokens per second

If you call countTokens with a text-and-video/audio input, it returns the combined token count of the text and the video/audio file in the input only ( totalTokens ). You can make this call before calling generateContent to check the size of your requests. You can also optionally call countTokens on the text and the file separately.

Another option is calling generateContent and then using the usageMetadata attribute on the response object to get the following:

  • The separate token counts of the input ( promptTokenCount ) and the output ( candidatesTokenCount )
  • The total number of tokens in both the input and the output ( totalTokenCount )
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt = "Tell me about this video";
let videoFile = await ai.files.upload({
  file: path.join(media, "Big_Buck_Bunny.mp4"),
  config: { mimeType: "video/mp4" },
});

// Poll until the video file is completely processed (state becomes ACTIVE).
while (!videoFile.state || videoFile.state.toString() !== "ACTIVE") {
  console.log("Processing video...");
  console.log("File state: ", videoFile.state);
  await sleep(5000);
  videoFile = await ai.files.get({ name: videoFile.name });
}

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(videoFile.uri, videoFile.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);

const generateResponse = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    prompt,
    createPartFromUri(videoFile.uri, videoFile.mimeType),
  ]),
});
console.log(generateResponse.usageMetadata);

System instructions and tools

System instructions and tools also count towards the total token count for the input.

If you use system instructions, the totalTokens count increases to reflect the addition of systemInstruction .

If you use function calling, the totalTokens count increases to reflect the addition of tools .