Gemini dhe modele të tjera gjeneruese të AI përpunojnë hyrjen dhe daljen në një shkallëzim të quajtur token .
Rreth argumenteve
Shenjat mund të jenë karaktere të vetme si z
ose fjalë të tëra si cat
. Fjalët e gjata ndahen në disa shenja. Grupi i të gjithë shenjave të përdorura nga modeli quhet fjalor, dhe procesi i ndarjes së tekstit në token quhet tokenizimi .
Për modelet Gemini, një shenjë është e barabartë me rreth 4 karaktere. 100 argumente janë të barabarta me rreth 60-80 fjalë angleze.
Kur faturimi është i aktivizuar, kostoja e një telefonate në API të Gemini përcaktohet pjesërisht nga numri i kodeve hyrëse dhe dalëse, kështu që të dish se si të numërosh argumentet mund të jetë e dobishme.
Numëroni argumentet
Të gjitha hyrjet dhe daljet nga Gemini API janë të tokenizuara, duke përfshirë tekstin, skedarët e imazheve dhe modalitete të tjera jo tekstuale.
Ju mund të numëroni argumentet në mënyrat e mëposhtme:
Thirrni
countTokens
me hyrjen e kërkesës.
Kjo kthen numrin total të shenjave vetëm në hyrje . Mund ta bëni këtë telefonatë përpara se të dërgoni hyrjen te modeli për të kontrolluar madhësinë e kërkesave tuaja.Përdorni atributin
usageMetadata
në objektinresponse
pasi të keni thirrurgenerate_content
.
Kjo kthen numrin total të argumenteve si në hyrje ashtu edhe në dalje :totalTokenCount
.
Gjithashtu kthen numërimin e shenjave të hyrjes dhe daljes veçmas:promptTokenCount
(shenjat hyrëse) dhecandidatesTokenCount
(shenjat dalëse).
Numëroni shenjat e tekstit
Nëse thërrisni countTokens
me një hyrje vetëm me tekst, ai kthen numrin e shenjave të tekstit vetëm në hyrje ( totalTokens
). Mund ta bëni këtë telefonatë përpara se të telefononi generateContent
për të kontrolluar madhësinë e kërkesave tuaja.
Një tjetër opsion është thirrja e generateContent
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numërimet e veçanta të shenjave të hyrjes (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i argumenteve si në hyrje ashtu edhe në dalje (
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);
Numëroni argumentet me shumë kthesa (chat).
Nëse quani countTokens
me historikun e bisedës, ai kthen numrin total të shenjave të tekstit nga çdo rol në bisedë ( totalTokens
).
Një tjetër opsion është thirrja e sendMessage
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numërimet e veçanta të shenjave të hyrjes (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i argumenteve si në hyrje ashtu edhe në dalje (
totalTokenCount
)
Për të kuptuar se sa e madhe do të jetë radha juaj e radhës në bisedë, duhet ta bashkëngjitni atë në histori kur telefononi 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,
);
Numëroni shenjat multimodale
Të gjitha hyrjet në Gemini API janë tokenizuar, duke përfshirë tekstin, skedarët e imazhit dhe modalitete të tjera jo tekstuale. Vini re pikat kryesore të mëposhtme të nivelit të lartë në lidhje me tokenizimin e hyrjes multimodale gjatë përpunimit nga Gemini API:
Me Gemini 2.0, hyrjet e imazhit me të dy dimensionet <=384 piksele llogariten si 258 shenja. Imazhet më të mëdha në një ose të dy dimensionet priten dhe shkallëzohen sipas nevojës në pllaka prej 768x768 pikselësh, secila e llogaritur si 258 shenja. Përpara Gemini 2.0, imazhet përdornin 258 shenja fikse.
Skedarët video dhe audio konvertohen në token me normat e mëposhtme fikse: video me 263 token për sekondë dhe audio me 32 argumente për sekondë.
Skedarët e imazhit
Nëse quani countTokens
me një hyrje tekst-dhe-imazh, ai kthen numrin e kombinuar të shenjave të tekstit dhe imazhit vetëm në hyrje ( totalTokens
). Mund ta bëni këtë telefonatë përpara se të telefononi generateContent
për të kontrolluar madhësinë e kërkesave tuaja. Ju gjithashtu mund të telefononi opsionalisht countTokens
në tekst dhe skedar veçmas.
Një tjetër opsion është thirrja e generateContent
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numërimet e veçanta të shenjave të hyrjes (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i argumenteve si në hyrje ashtu edhe në dalje (
totalTokenCount
)
Shembull që përdor një imazh të ngarkuar nga 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);
Shembull që ofron imazhin si të dhëna inline:
// 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);
Skedarët video ose audio
Audio dhe video konvertohen secila në token me tarifat fikse të mëposhtme:
- Video: 263 argumente në sekondë
- Audio: 32 shenja në sekondë
Nëse thërrisni countTokens
me një hyrje tekst-dhe-video/audio, ai kthen numërimin e kombinuar të tokenit të tekstit dhe skedarit video/audio vetëm në hyrje ( totalTokens
). Mund ta bëni këtë telefonatë përpara se të telefononi generateContent
për të kontrolluar madhësinë e kërkesave tuaja. Ju gjithashtu mund të telefononi opsionalisht countTokens
në tekst dhe skedar veçmas.
Një tjetër opsion është thirrja e generateContent
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numërimet e veçanta të shenjave të hyrjes (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i argumenteve si në hyrje ashtu edhe në dalje (
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);
Udhëzimet dhe mjetet e sistemit
Udhëzimet dhe mjetet e sistemit llogariten gjithashtu në numrin total të shenjave për hyrjen.
Nëse përdorni udhëzime të sistemit, numri totalTokens
rritet për të pasqyruar shtimin e systemInstruction
.
Nëse përdorni thirrjen e funksionit, numri totalTokens
rritet për të pasqyruar shtimin e tools
.
Binjakët dhe modelet e tjera gjeneruese të AI përpunojnë hyrjen dhe daljen në një kokrrizë të quajtur një shenjë .
Rreth Tokens
Shenjat mund të jenë personazhe të vetëm si z
ose fjalë të tëra si cat
. Fjalët e gjata ndahen në disa shenja. Seti i të gjitha shenjave të përdorura nga modeli quhet fjalori, dhe procesi i ndarjes së tekstit në shenja quhet tokenization .
Për modelet e Binjakëve, një shenjë është e barabartë me rreth 4 karaktere. 100 shenja janë të barabarta me rreth 60-80 fjalë angleze.
Kur aktivizohet faturimi, kostoja e një thirrje në API të Binjakëve përcaktohet pjesërisht nga numri i shenjave të hyrjes dhe daljes, kështu që të dish se si të numërosh shenjat mund të jetë e dobishme.
Numër toke
Të gjitha inputet dhe dalja nga API Binjakët janë të shenjuara, përfshirë tekstin, skedarët e imazhit dhe modalitetet e tjera jo-teksti.
Ju mund të numëroni shenjat në mënyrat e mëposhtme:
Thirrni
countTokens
me kontributin e kërkesës.
Kjo kthen numrin e përgjithshëm të shenjave vetëm në hyrje . Ju mund ta bëni këtë telefonatë përpara se të dërgoni hyrjen në model për të kontrolluar madhësinë e kërkesave tuaja.Përdorni atributin
usageMetadata
në objektinresponse
pas thirrjesgenerate_content
.
Kjo kthen numrin e përgjithshëm të shenjave si në input ashtu edhe në dalje :totalTokenCount
.
Ai gjithashtu kthen akuzat e shenjave të hyrjes dhe daljes veç e veç:promptTokenCount
(Tokens Input) dhecandidatesTokenCount
(Tokens Output).
Numëroni shenjat e tekstit
Nëse i quani countTokens
me një input vetëm me tekst, ai kthen numërimin e shenjës së tekstit vetëm në hyrje ( totalTokens
). Ju mund ta bëni këtë telefonatë përpara se të telefononi generateContent
për të kontrolluar madhësinë e kërkesave tuaja.
Një tjetër mundësi është thirrja e generateContent
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numrat e ndara të shenjës së inputit (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i shenjave si në hyrje ashtu edhe në dalje (
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);
Numëroni shenjat me shumë kthesa (chat)
Nëse i quani countTokens
me historinë e bisedës, ajo kthen numrin total të shenjave të tekstit nga secili rol në bisedë ( totalTokens
).
Një tjetër mundësi është thirrja e sendMessage
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numrat e ndara të shenjës së inputit (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i shenjave si në hyrje ashtu edhe në dalje (
totalTokenCount
)
Për të kuptuar se sa e madhe do të jetë kthesa juaj e ardhshme bisedore, ju duhet ta bashkoni atë në histori kur i quani 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,
);
Numëroni shenjat multimodale
Të gjitha inputet në API të Binjakëve janë të shenjta, përfshirë tekstin, skedarët e figurave dhe modalitetet e tjera jo-teksti. Vini re pikat kryesore të nivelit të lartë të nivelit të lartë në lidhje me tokenizimin e inputit multimodal gjatë përpunimit nga API i Binjakëve:
Me Binjakët 2.0, inputet e figurës me të dy dimensionet <= 384 piksele llogariten si 258 shenja. Imazhet më të mëdha në njërën ose të dy dimensionet janë të prera dhe të shkallëzuara sipas nevojës në pllaka prej 768x768 piksele, secila llogaritet si 258 shenja. Para Gemini 2.0, imazhet përdorën një 258 shenja fikse.
Skedarët video dhe audio shndërrohen në shenja me tarifat fikse të mëposhtme: video në 263 shenja për sekondë dhe audio në 32 shenja për sekondë.
Skedarët e imazheve
Nëse i quani countTokens
me një hyrje të tekstit dhe imazhit, ai kthen numërimin e kombinuar të shenjës së tekstit dhe imazhin vetëm në hyrje ( totalTokens
). Ju mund ta bëni këtë telefonatë përpara se të telefononi generateContent
për të kontrolluar madhësinë e kërkesave tuaja. Ju gjithashtu mund të telefononi në mënyrë opsionale countTokens
në tekst dhe skedarin veç e veç.
Një tjetër mundësi është thirrja e generateContent
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numrat e ndara të shenjës së inputit (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i shenjave si në hyrje ashtu edhe në dalje (
totalTokenCount
)
Shembull që përdor një imazh të ngarkuar nga API i skedarit:
// 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);
Shembull që siguron imazhin si të dhëna inline:
// 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);
Skedarë video ose audio
Audio dhe video janë secila konvertuar në shenja me tarifat fikse të mëposhtme:
- VIDEO: 263 Tokens për sekondë
- Audio: 32 Tokens për sekondë
Nëse i quani countTokens
me një input tekst-dhe-video/audio, ai kthen numërimin e kombinuar të shenjës së tekstit dhe skedarin video/audio në vetëm input ( totalTokens
). Ju mund ta bëni këtë telefonatë përpara se të telefononi generateContent
për të kontrolluar madhësinë e kërkesave tuaja. Ju gjithashtu mund të telefononi në mënyrë opsionale countTokens
në tekst dhe skedarin veç e veç.
Një tjetër mundësi është thirrja e generateContent
dhe më pas përdorimi i atributit usageMetadata
në objektin response
për të marrë sa vijon:
- Numrat e ndara të shenjës së inputit (
promptTokenCount
) dhe daljes (candidatesTokenCount
) - Numri i përgjithshëm i shenjave si në hyrje ashtu edhe në dalje (
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);
Udhëzimet dhe mjetet e sistemit
Udhëzimet dhe mjetet e sistemit gjithashtu llogariten drejt numërimit të përgjithshëm të shenjave për inputin.
Nëse përdorni udhëzime të sistemit, numërimi i totalTokens
rritet për të pasqyruar shtimin e systemInstruction
.
Nëse përdorni thirrjen e funksionit, numërimi i totalTokens
rritet për të pasqyruar shtimin e 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 theresponse
object after callinggenerate_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) andcandidatesTokenCount
(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
.