Tokenization¶
Two ways to count tokens: server-side counting via client.tokenization().count(...), and a
fully offline local BPE tokenizer via TokenizerFactory.qwen(). Adapted from
TokenizationCount
and
TokenizationLocalCount.
Full runnable example: TokenizationCount.java (auto-synced)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.chat;
import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.messages.Message;
import com.alibaba.dashscope.types.tokenization.TokenCount;
import com.alibaba.dashscope.types.tokenization.TokenizationCountParams;
import java.util.Arrays;
/**
* Server-side token counting over a plain prompt and over a chat message list. Translation of the
* Python blueprint example 01_atomic_capabilities/text_generation/tokenization.py.
*
* <p>For the local BPE tokenizer (no network) see {@link TokenizationLocalCount}.
*/
public final class TokenizationCount {
public static void main(String[] args) throws Exception {
String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen3.7-plus");
try (DashScopeClient client = ExampleSupport.client()) {
// Count the tokens of a plain prompt
System.out.println("----- count (prompt) -----");
TokenCount resp =
client
.tokenization()
.count(TokenizationCountParams.builder().model(model).prompt("请用一句话介绍杭州").build());
System.out.println("input_tokens: " + resp.getInputTokens());
System.out.println("token_ids: " + resp.getTokenIds());
// Count the tokens of a chat message list
System.out.println("----- count (messages) -----");
resp =
client
.tokenization()
.count(
TokenizationCountParams.builder()
.model(model)
.messages(
Arrays.asList(
Message.system("You are a helpful assistant."),
Message.user("请用一句话介绍杭州")))
.build());
System.out.println("input_tokens: " + resp.getInputTokens());
}
}
}
Full runnable example: TokenizationLocalCount.java (auto-synced)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.chat;
import com.alibaba.dashscope.tokenization.Tokenizer;
import com.alibaba.dashscope.tokenization.TokenizerFactory;
import java.util.List;
/**
* Local Qwen BPE tokenizer: encode/decode entirely offline, no API key and no network call (the
* vocabulary {@code qwen.tiktoken} is resolved from {@code DASHSCOPE_QWEN_VOCAB}, the classpath, a
* verified local cache, or a one-time ModelScope download).
*
* <p>For server-side counting see {@link TokenizationCount}. Local results are approximate: they
* are not guaranteed to match the model's own tokenization exactly.
*/
public final class TokenizationLocalCount {
public static void main(String[] args) {
Tokenizer tokenizer = TokenizerFactory.qwen();
// Ordinary encoding: special tokens in the text are treated as plain text.
System.out.println("----- encodeOrdinary -----");
String text = "你好,杭州!";
List<Integer> ids = tokenizer.encodeOrdinary(text);
System.out.println("text: " + text);
System.out.println("token count: " + ids.size());
System.out.println("token_ids: " + ids);
System.out.println("decoded: " + tokenizer.decode(ids));
// Special-token-aware encoding: "all" recognizes <|im_start|> / <|im_end|> etc. as single
// tokens; "none" forbids them, "none_raise" throws when the input has none.
System.out.println("----- encode (special tokens) -----");
String chatText = "<|im_start|>user\n你好<|im_end|>";
List<Integer> chatIds = tokenizer.encode(chatText, "all");
System.out.println("text: " + chatText.replace("\n", "\\n"));
System.out.println("token count: " + chatIds.size());
System.out.println("decoded: " + tokenizer.decode(chatIds).replace("\n", "\\n"));
}
}
Server-side counting¶
Count a plain prompt or a full chat message list:
import com.alibaba.dashscope.types.tokenization.TokenCount;
import com.alibaba.dashscope.types.tokenization.TokenizationCountParams;
TokenCount resp = client.tokenization().count(
TokenizationCountParams.builder()
.model("qwen-plus")
.prompt("Introduce Hangzhou in one sentence")
.build());
System.out.println("input_tokens: " + resp.getInputTokens());
System.out.println("token_ids: " + resp.getTokenIds());
// Or over messages:
resp = client.tokenization().count(
TokenizationCountParams.builder()
.model("qwen-plus")
.messages(Arrays.asList(
Message.system("You are a helpful assistant."),
Message.user("Introduce Hangzhou in one sentence")))
.build());
Local BPE tokenizer (offline)¶
TokenizerFactory.qwen() needs no API key and no network call:
import com.alibaba.dashscope.tokenization.Tokenizer;
import com.alibaba.dashscope.tokenization.TokenizerFactory;
import java.util.List;
Tokenizer tokenizer = TokenizerFactory.qwen();
// Ordinary encoding: special tokens in the text are treated as plain text.
List<Integer> ids = tokenizer.encodeOrdinary("你好,杭州!");
System.out.println("token count: " + ids.size());
System.out.println("decoded: " + tokenizer.decode(ids));
// Special-token-aware encoding: "all" recognizes <|im_start|> / <|im_end|> as single tokens.
List<Integer> chatIds = tokenizer.encode("<|im_start|>user\n你好<|im_end|>", "all");
encode(text, mode) accepts "all", "none" (forbid special tokens), and "none_raise"
(throws NoSpecialTokenException when the input contains no special token).
Vocabulary resolution¶
The qwen.tiktoken vocabulary is resolved in order from:
DASHSCOPE_QWEN_VOCAB(path to a vocab file — useful for hermetic tests),- the classpath,
- a verified local cache,
- a one-time ModelScope download.
Approximation
Local results are approximate: they are not guaranteed to match the model's own tokenization exactly. Use server-side counting when exact billing-relevant counts matter.