|
| 1 | +// Copyright 2024 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// [START generativeaionvertexai_gemini_token_count] |
| 16 | +const {GoogleGenAI} = require('@google/genai'); |
| 17 | + |
| 18 | +/** |
| 19 | + * TODO(developer): Update these variables before running the sample. |
| 20 | + */ |
| 21 | +async function countTokens( |
| 22 | + projectId = 'PROJECT_ID', |
| 23 | + location = 'us-central1', |
| 24 | + model = 'gemini-2.5-flash' |
| 25 | +) { |
| 26 | + // Initialize the client with your Cloud project and location |
| 27 | + const client = new GoogleGenAI({ |
| 28 | + vertexai: true, |
| 29 | + project: projectId, |
| 30 | + location: location, |
| 31 | + }); |
| 32 | + |
| 33 | + const contents = [ |
| 34 | + {role: 'user', parts: [{text: 'How are you doing today?'}]}, |
| 35 | + ]; |
| 36 | + |
| 37 | + // Prompt tokens count |
| 38 | + const countTokensResp = await client.models.countTokens({ |
| 39 | + model: model, |
| 40 | + contents: contents, |
| 41 | + }); |
| 42 | + console.log('Prompt tokens count: ', countTokensResp); |
| 43 | + |
| 44 | + // Send text to gemini |
| 45 | + const result = await client.models.generateContent({ |
| 46 | + model: model, |
| 47 | + contents: contents, |
| 48 | + }); |
| 49 | + |
| 50 | + // Response tokens count |
| 51 | + const usageMetadata = result.usageMetadata; |
| 52 | + console.log('Response tokens count: ', usageMetadata); |
| 53 | +} |
| 54 | +// [END generativeaionvertexai_gemini_token_count] |
| 55 | + |
| 56 | +countTokens(...process.argv.slice(2)).catch(err => { |
| 57 | + console.error(err.message); |
| 58 | + process.exitCode = 1; |
| 59 | +}); |
0 commit comments