Skip to main content
The Tokenizer class handles text encoding and decoding for language models.

Constructor

Create a tokenizer from a model.
Model
required
The Model object to create the tokenizer from

Properties

bos_token_id

The beginning-of-sequence token ID.
int
Token ID for the start of a sequence

eos_token_ids

Array of end-of-sequence token IDs.
numpy.ndarray
Array of token IDs that mark the end of generation

pad_token_id

The padding token ID.
int
Token ID used for padding sequences

Methods

encode()

Encode a string into token IDs.
str
required
The text to encode
numpy.ndarray
Array of int32 token IDs

decode()

Decode token IDs back into text.
numpy.ndarray
required
Array of int32 token IDs to decode
str
The decoded text string

encode_batch()

Encode multiple strings at once.
list[str]
required
List of text strings to encode
OgaTensor
Tensor containing all encoded sequences

decode_batch()

Decode multiple token sequences at once.
OgaTensor
required
Tensor containing token sequences to decode
list[str]
List of decoded text strings

to_token_id()

Convert a token string to its ID.
str
required
The token string to convert
int
The token ID

apply_chat_template()

Apply a chat template to format messages.
str
required
JSON-serialized list of message dictionaries with “role” and “content” fields
str
default:"None"
Custom Jinja template string (uses model’s default if not provided)
str
default:"None"
JSON-serialized list of tool definitions
bool
default:"True"
Whether to add tokens indicating the assistant’s turn to respond
str
The formatted prompt ready for encoding

create_stream()

Create a streaming tokenizer for incremental decoding.
TokenizerStream
A TokenizerStream object for streaming decoding

update_options()

Update tokenizer options dynamically.
dict
Key-value pairs of tokenizer options to update

TokenizerStream

Streaming decoder for incremental token-by-token decoding.

decode()

Decode a single token and return the corresponding text chunk.
int
required
The token ID to decode
str
The text fragment for this token (may be empty for partial multi-byte characters)

Example Usage

Basic encoding and decoding:
Streaming generation:
Batch encoding:
Chat template: