Loading...
const inputTokens = Math.ceil(JSON.stringify(messages).length / 4);
if (inputTokens > LIMIT) trimHistory(messages);const res = await fetch('https://api.example.com/v1/count-tokens', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: MODEL, messages })
});
const { inputTokens } = await res.json();
if (inputTokens > LIMIT) trimHistory(messages);The count comes from the target model's own token counting, not a characters-divided-by-four guess that can be far off.
Each model family has its own tokenizer with its own vocabulary, so the same text can split into a different number of tokens.
Byte pair encoding builds a vocabulary by merging the most frequent pairs of characters or bytes into tokens, step by step.
The model sees tokens, not letters. A word may be one token, so the model has no direct view of its individual characters.