Skip to content

Commit 76cda15

Browse files
feat(genai): Add Count Tokens Samples (#13155)
* init count_tokens * Add Count Tokens Samples * Update client ot use GA endpoint * Update genai/count_tokens/count_tokens_compute_with_txt.py Co-authored-by: Sampath Kumar <sampathm@google.com> * Update genai/count_tokens/count_tokens_resp_with_txt.py Co-authored-by: Sampath Kumar <sampathm@google.com> * Update genai/count_tokens/count_tokens_with_txt.py Co-authored-by: Sampath Kumar <sampathm@google.com> * Update genai/count_tokens/count_tokens_with_txt.py Co-authored-by: Sampath Kumar <sampathm@google.com> * Lint --------- Co-authored-by: Sampath Kumar <sampathm@google.com>
1 parent 1f1b4dd commit 76cda15

8 files changed

+257
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Copyright 2025 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+
16+
def compute_tokens() -> int:
17+
# [START googlegenaisdk_count_tokens_compute_with_txt]
18+
from google import genai
19+
from google.genai.types import HttpOptions
20+
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
22+
response = client.models.compute_tokens(
23+
model="gemini-2.0-flash-001",
24+
contents="What's the longest word in the English language?",
25+
)
26+
print(response)
27+
28+
# Example output:
29+
# tokens_info=[TokensInfo(
30+
# role='user',
31+
# token_ids=[1841, 235303, 235256, 573, 32514, 2204, 575, 573, 4645, 5255, 235336],
32+
# tokens=[b'What', b"'", b's', b' the', b' longest', b' word', b' in', b' the', b' English', b' language', b'?']
33+
# )]
34+
35+
# [END googlegenaisdk_count_tokens_compute_with_txt]
36+
return response.tokens_info
37+
38+
39+
if __name__ == "__main__":
40+
compute_tokens()
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Copyright 2025 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+
16+
def generate_content() -> int:
17+
# [START googlegenaisdk_count_tokens_resp_with_txt]
18+
from google import genai
19+
from google.genai.types import HttpOptions
20+
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
22+
23+
prompt = "Why is the sky blue?"
24+
25+
# Send text to Gemini
26+
response = client.models.generate_content(
27+
model="gemini-2.0-flash-001", contents=prompt
28+
)
29+
30+
# Prompt and response tokens count
31+
print(response.usage_metadata)
32+
33+
# Example output:
34+
# cached_content_token_count=None
35+
# candidates_token_count=311
36+
# prompt_token_count=6
37+
# total_token_count=317
38+
39+
# [END googlegenaisdk_count_tokens_resp_with_txt]
40+
return response.usage_metadata
41+
42+
43+
if __name__ == "__main__":
44+
generate_content()
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Copyright 2025 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+
16+
def count_tokens() -> int:
17+
# [START googlegenaisdk_count_tokens_with_txt]
18+
from google import genai
19+
from google.genai.types import HttpOptions
20+
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
22+
response = client.models.count_tokens(
23+
model="gemini-2.0-flash-001",
24+
contents="What's the highest mountain in Africa?",
25+
)
26+
print(response)
27+
# Example output:
28+
# total_tokens=10
29+
# cached_content_token_count=None
30+
31+
# [END googlegenaisdk_count_tokens_with_txt]
32+
return response.total_tokens
33+
34+
35+
if __name__ == "__main__":
36+
count_tokens()
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Copyright 2025 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+
16+
def count_tokens() -> int:
17+
# [START googlegenaisdk_count_tokens_with_txt_img_vid]
18+
from google import genai
19+
from google.genai.types import HttpOptions, Part
20+
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
22+
23+
contents = [
24+
Part.from_uri(
25+
file_uri="gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
26+
mime_type="video/mp4",
27+
),
28+
"Provide a description of the video.",
29+
]
30+
31+
response = client.models.count_tokens(
32+
model="gemini-2.0-flash-001",
33+
contents=contents,
34+
)
35+
print(response)
36+
37+
# Example output:
38+
# total_tokens=10 cached_content_token_count=None
39+
40+
# [END googlegenaisdk_count_tokens_with_txt_img_vid]
41+
return response.total_tokens
42+
43+
44+
if __name__ == "__main__":
45+
count_tokens()

genai/count_tokens/noxfile_config.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Copyright 2021 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+
# http://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+
# Default TEST_CONFIG_OVERRIDE for python repos.
16+
17+
# You can copy this file into your directory, then it will be imported from
18+
# the noxfile.py.
19+
20+
# The source of truth:
21+
# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/noxfile_config.py
22+
23+
TEST_CONFIG_OVERRIDE = {
24+
# You can opt out from the test for specific Python versions.
25+
"ignored_versions": ["2.7", "3.7", "3.8", "3.10", "3.11", "3.12"],
26+
# Old samples are opted out of enforcing Python type hints
27+
# All new samples should feature them
28+
"enforce_type_hints": True,
29+
# An envvar key for determining the project id to use. Change it
30+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
31+
# build specific Cloud project. You can also use your own string
32+
# to use your own Cloud project.
33+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
34+
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
35+
# If you need to use a specific version of pip,
36+
# change pip_version_override to the string representation
37+
# of the version number, for example, "20.2.4"
38+
"pip_version_override": None,
39+
# A dictionary you want to inject into your test. Don't put any
40+
# secrets here. These values will override predefined values.
41+
"envs": {},
42+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
backoff==2.2.1
2+
google-api-core==2.19.0
3+
pytest==8.2.0
4+
pytest-asyncio==0.23.6

genai/count_tokens/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
google-genai==1.2.0
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Copyright 2025 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+
#
16+
# Using Google Cloud Vertex AI to test the code samples.
17+
#
18+
19+
import os
20+
21+
import count_tokens_compute_with_txt
22+
import count_tokens_resp_with_txt
23+
import count_tokens_with_txt
24+
import count_tokens_with_txt_img_vid
25+
26+
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
27+
os.environ["GOOGLE_CLOUD_LOCATION"] = "us-central1"
28+
# The project name is included in the CICD pipeline
29+
# os.environ['GOOGLE_CLOUD_PROJECT'] = "add-your-project-name"
30+
31+
32+
def test_count_tokens_compute_with_txt() -> None:
33+
assert count_tokens_compute_with_txt.compute_tokens()
34+
35+
36+
def test_count_tokens_resp_with_txt() -> None:
37+
assert count_tokens_resp_with_txt.generate_content()
38+
39+
40+
def test_count_tokens_with_txt() -> None:
41+
assert count_tokens_with_txt.count_tokens()
42+
43+
44+
def test_count_tokens_with_txt_img_vid() -> None:
45+
assert count_tokens_with_txt_img_vid.count_tokens()

0 commit comments

Comments
 (0)