-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat: add new GenAI SDK count tokens samples #10145
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
jdomingr
wants to merge
6
commits into
GoogleCloudPlatform:main
Choose a base branch
from
jdomingr:genai-sdk-counttokens-samples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+177
−5
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1a3ba8a
remove unused imports
71b68e5
feat: add new GenAI count tokens samples
09f6237
feat: add new tests for count tokens samples
a5cd24e
refactor: add new asserts to make sure CountTokensReponseWithText ret…
e434f5b
refactor: update compute tokens to change logic that prints tokens info
7c28d74
fix controlled generation test case
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
80 changes: 80 additions & 0 deletions
80
genai/snippets/src/main/java/genai/counttokens/CountTokensComputeWithText.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
/* | ||
* Copyright 2025 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package genai.counttokens; | ||
|
||
// [START googlegenaisdk_counttoken_compute_with_txt] | ||
|
||
import com.google.genai.Client; | ||
import com.google.genai.types.ComputeTokensResponse; | ||
import com.google.genai.types.HttpOptions; | ||
import com.google.genai.types.TokensInfo; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.Optional; | ||
|
||
public class CountTokensComputeWithText { | ||
|
||
public static void main(String[] args) { | ||
// TODO(developer): Replace these variables before running the sample. | ||
String modelId = "gemini-2.5-flash"; | ||
computeTokens(modelId); | ||
} | ||
|
||
// Computes tokens with text input | ||
public static Optional<List<TokensInfo>> computeTokens(String modelId) { | ||
// Initialize client that will be used to send requests. This client only needs to be created | ||
// once, and can be reused for multiple requests. | ||
try (Client client = | ||
Client.builder() | ||
.location("global") | ||
.vertexAI(true) | ||
.httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
.build()) { | ||
|
||
ComputeTokensResponse response = client.models.computeTokens( | ||
modelId, "What's the longest word in the English language?", null); | ||
|
||
// Get tokensInfo from the response | ||
List<TokensInfo> tokensInfo = response.tokensInfo().orElse(new ArrayList<>()); | ||
// Print TokensInfo | ||
tokensInfo.forEach( | ||
info -> { | ||
info.role().ifPresent(role -> System.out.println("role: " + role)); | ||
info.tokenIds().ifPresent(tokenIds -> System.out.println("tokenIds: " + tokenIds)); | ||
// print tokens input as strings since they are in a form of byte array | ||
System.out.println("tokens: "); | ||
info.tokens().ifPresent(tokens -> | ||
tokens.forEach(token -> | ||
System.out.println(new String(token, StandardCharsets.UTF_8)) | ||
) | ||
); | ||
} | ||
); | ||
// Example response.tokensInfo() | ||
// role: user | ||
// tokenIds: [1841, 235303, 235256, 573, 32514, 2204, 575, 573, 4645, 5255, 235336] | ||
// tokens: | ||
// What | ||
// ' | ||
// s | ||
// the | ||
return response.tokensInfo(); | ||
} | ||
} | ||
} | ||
// [END googlegenaisdk_counttoken_compute_with_txt] |
63 changes: 63 additions & 0 deletions
63
genai/snippets/src/main/java/genai/counttokens/CountTokensResponseWithText.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
/* | ||
* Copyright 2025 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package genai.counttokens; | ||
|
||
// [START googlegenaisdk_counttoken_resp_with_txt] | ||
|
||
import com.google.genai.Client; | ||
import com.google.genai.types.GenerateContentResponse; | ||
import com.google.genai.types.GenerateContentResponseUsageMetadata; | ||
import com.google.genai.types.HttpOptions; | ||
import java.util.Optional; | ||
|
||
public class CountTokensResponseWithText { | ||
|
||
public static void main(String[] args) { | ||
// TODO(developer): Replace these variables before running the sample. | ||
String modelId = "gemini-2.5-flash"; | ||
countTokens(modelId); | ||
} | ||
|
||
// Generates content response usage metadata that contains prompt and response token counts | ||
public static Optional<GenerateContentResponseUsageMetadata> countTokens(String modelId) { | ||
// Initialize client that will be used to send requests. This client only needs to be created | ||
// once, and can be reused for multiple requests. | ||
try (Client client = | ||
Client.builder() | ||
.location("global") | ||
.vertexAI(true) | ||
.httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
.build()) { | ||
|
||
GenerateContentResponse response = | ||
client.models.generateContent(modelId, "Why is the sky blue?", null); | ||
|
||
response.usageMetadata().ifPresent(System.out::println); | ||
// Example response: | ||
// GenerateContentResponseUsageMetadata{cacheTokensDetails=Optional.empty, | ||
// cachedContentTokenCount=Optional.empty, candidatesTokenCount=Optional[569], | ||
// candidatesTokensDetails=Optional[[ModalityTokenCount{modality=Optional[TEXT], | ||
// tokenCount=Optional[569]}]], promptTokenCount=Optional[6], | ||
// promptTokensDetails=Optional[[ModalityTokenCount{modality=Optional[TEXT], | ||
// tokenCount=Optional[6]}]], thoughtsTokenCount=Optional[1132], | ||
// toolUsePromptTokenCount=Optional.empty, toolUsePromptTokensDetails=Optional.empty, | ||
// totalTokenCount=Optional[1707], trafficType=Optional[ON_DEMAND]} | ||
return response.usageMetadata(); | ||
} | ||
} | ||
} | ||
// [END googlegenaisdk_counttoken_resp_with_txt] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.