|
| 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 | +import os |
| 15 | + |
| 16 | +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") |
| 17 | + |
| 18 | + |
| 19 | +def list_tokens_example() -> int: |
| 20 | + # [START generativeaionvertexai_compute_tokens] |
| 21 | + from vertexai.preview.tokenization import get_tokenizer_for_model |
| 22 | + |
| 23 | + # init local tokenzier |
| 24 | + tokenizer = get_tokenizer_for_model("gemini-1.5-flash-001") |
| 25 | + |
| 26 | + # Count Tokens |
| 27 | + prompt = "why is the sky blue?" |
| 28 | + response = tokenizer.count_tokens(prompt) |
| 29 | + print(f"Tokens count: {response.total_tokens}") |
| 30 | + # Example response: |
| 31 | + # Tokens count: 6 |
| 32 | + |
| 33 | + # Compute Tokens |
| 34 | + response = tokenizer.compute_tokens(prompt) |
| 35 | + print(f"Tokens list: {response.tokens_info}") |
| 36 | + # Example response: |
| 37 | + # Tokens list: [TokensInfo(token_ids=[18177, 603, 573, 8203, 3868, 235336], |
| 38 | + # tokens=[b'why', b' is', b' the', b' sky', b' blue', b'?'], role='user')] |
| 39 | + # [END generativeaionvertexai_compute_tokens] |
| 40 | + return len(response.tokens_info) |
| 41 | + |
| 42 | + |
| 43 | +if __name__ == "__main__": |
| 44 | + list_tokens_example() |
0 commit comments