# Tokenizer

> The Tokenizer is a component that splits text into tokens and converts them into numbers for a language model.

## What is a tokenizer and how do I count tokens?

The component that splits text into tokens and maps each of them to a number the model understands. Different models use different tokenizers, so the same text can take a different number of tokens.

- Topic: Language Models
- Type: tool

## Example

Wrong:

```js
const inputTokens = Math.ceil(JSON.stringify(messages).length / 4);
if (inputTokens > LIMIT) trimHistory(messages);
```

Right:

```js
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.

## Common mistakes

- Using one model's tokenizer to count tokens for another model.

## Key points

- Tokens are counted with the tokenizer or token counting endpoint of the target model.
- Token counts are not estimated as characters divided by four when a limit must be exact.
- Counts are recalculated when the app switches to a model with a different tokenizer.

## Interview questions

### Why do different models count tokens differently?

Each model family has its own tokenizer with its own vocabulary, so the same text can split into a different number of tokens.

### What is BPE tokenization?

Byte pair encoding builds a vocabulary by merging the most frequent pairs of characters or bytes into tokens, step by step.

### Why do LLMs struggle to count letters in a word?

The model sees tokens, not letters. A word may be one token, so the model has no direct view of its individual characters.

## Related cards

- [Token](https://wonderium.dev/ai/token.md)
- [Context Window](https://wonderium.dev/ai/context-window.md)
- [Token Cost](https://wonderium.dev/ai/token-cost.md)
- [Chunking](https://wonderium.dev/ai/chunking.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/tokenizer
- Last updated: 2026-11-25
