Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat(genai): Demonstrate how to get token count #13428

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions genai/count_tokens/counttoken_compute_with_txt.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ def compute_tokens_example() -> int:
)

print(response)
print(f"token count: {len(response.tokens_info[0].tokens)}")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To handle cases where response.tokens_info might be empty or contain multiple elements, consider summing the token counts from all TokensInfo objects within response.tokens_info for a more robust approach.

print(f"token count: {sum(len(info.tokens) for info in response.tokens_info)}")

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that the suggestion is more approach but this is a pretty simple example. I don't think we need to complicate it with the fully robust solution. The goal here is to understand basic usage.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kaycebasques could you update the approach so that it does handle an empty response? The basic usage is the goal, and if it fails for whatever reason having the sample address it encourages the recommended practice.

# Example output:
# tokens_info=[TokensInfo(
# role='user',
# token_ids=[1841, 235303, 235256, 573, 32514, 2204, 575, 573, 4645, 5255, 235336],
# tokens=[b'What', b"'", b's', b' the', b' longest', b' word', b' in', b' the', b' English', b' language', b'?']
# )]
# token count: 11
# [END googlegenaisdk_counttoken_compute_with_txt]
return response.tokens_info

Expand Down