Skip to main content

Tokenization Service

The TokenizationService provides functionality to tokenize text using IBM watsonx.ai foundation models. It converts a text string into a sequence of tokens, returning the token count and optionally the individual token strings. Both synchronous and asynchronous invocation are supported.

Quick Start​

TokenizationService service = TokenizationService.builder()
.apiKey(WATSONX_API_KEY)
.projectId(WATSONX_PROJECT_ID)
.baseUrl(CloudRegion.DALLAS)
.modelId("ibm/granite-4-h-small")
.build();

TokenizationResponse response = service.tokenize("Tell me a joke");
System.out.println("Token count: " + response.result().tokenCount());
// → Token count: 4

Overview​

The TokenizationService enables you to:

  • Count the number of tokens a text string produces for a given model.
  • Retrieve the individual token strings with returnTokens(true).
  • Run tokenization synchronously or asynchronously via CompletableFuture.

Service Configuration​

Basic Setup​

TokenizationService service = TokenizationService.builder()
.apiKey(WATSONX_API_KEY)
.projectId(WATSONX_PROJECT_ID)
.baseUrl("https://us-south.ml.cloud.ibm.com") // or use CloudRegion
.modelId("ibm/granite-4-h-small")
.build();

Builder Parameters​

ParameterTypeRequiredDescription
apiKeyStringConditionalAPI key for IBM Cloud authentication
authenticatorAuthenticatorConditionalCustom authentication (alternative to apiKey)
projectIdStringConditionalProject ID where tokenization will run
spaceIdStringConditionalSpace ID (alternative to projectId)
modelIdStringYesFoundation model ID to use for tokenization
baseUrlString/CloudRegionYeswatsonx.ai service base URL
timeoutDurationNoRequest timeout (default: 60 seconds)
logRequestsBooleanNoEnable request logging (default: false)
logResponsesBooleanNoEnable response logging (default: false)
httpClientHttpClientNoCustom HTTP client
verifySslBooleanNoSSL certificate verification (default: true)
versionStringNoAPI version override

Either apiKey or authenticator must be provided. Either projectId or spaceId must be specified.


Examples​

Count Tokens​

Get the token count for a text string without retrieving the individual tokens:

TokenizationResponse response = service.tokenize("Write a tagline for an alumni association: Together we");
System.out.println("Token count: " + response.result().tokenCount());
// → Token count: 11

Retrieve Individual Tokens​

Set returnTokens(true) to get the list of token strings in addition to the count:

TokenizationParameters parameters = TokenizationParameters.builder()
.returnTokens(true)
.build();

TokenizationResponse response = service.tokenize("Write a tagline for an alumni association: Together we", parameters);
System.out.println("Count: " + response.result().tokenCount());
System.out.println("Tokens: " + response.result().tokens());
// → Count: 11
// → Tokens: [Write, a, tag, line, for, an, alumni, associ, ation:, Together, we]

Tokenization Parameters​

The TokenizationParameters class controls the tokenization behavior per request.

Builder Reference​

ParameterTypeDescription
returnTokensBooleanIf true, the response includes the list of individual token strings in addition to the count. Default: false (count only)
modelIdStringOverride the service-level model ID for this request
projectIdStringOverride the default Project ID
spaceIdStringOverride the default Space ID
transactionIdStringRequest tracking ID sent as a header for tracing
cryptoStringKey reference for encrypting the inference request (e.g., IBM Key Protect CRN)

toTokenizationRequestParameters() returns null if returnTokens is not set, so no parameters block is included in the request body.


TokenizationResponse​

FieldTypeDescription
modelId()StringIdentifier of the model used for tokenization
result()ResultThe tokenization result
result().tokenCount()intTotal number of tokens produced
result().tokens()List<String>Individual token strings. null if returnTokens was not set to true