Skip to main content
The Tokenizer class handles text encoding and decoding for language models. It converts text into token sequences that models can process and decodes token sequences back into readable text.

Constructor

Tokenizer(Model model)

Creates a tokenizer instance from a loaded model.
Model
required
The model to create a tokenizer for
Tokenizer.cs:14-17

Encoding Methods

Encode(string str)

Encodes a single string into a token sequence.
string
required
The text to encode
Returns: Sequences - A sequences object containing the encoded tokens
Tokenizer.cs:74-87

EncodeBatch(string[] strings)

Encodes multiple strings into token sequences.
string[]
required
Array of strings to encode
Returns: Sequences - A sequences object containing all encoded sequences
Tokenizer.cs:19-36

Decoding Methods

Decode(ReadOnlySpan<int> sequence)

Decodes a token sequence into a string.
ReadOnlySpan<int>
required
The token sequence to decode
Returns: string - The decoded text
Tokenizer.cs:89-107

DecodeBatch(Sequences sequences)

Decodes multiple token sequences into strings.
Sequences
required
The sequences to decode
Returns: string[] - Array of decoded strings
Tokenizer.cs:38-47

Chat Template Methods

ApplyChatTemplate(string template_str, string messages, string tools, bool add_generation_prompt)

Applies a chat template to format messages for the model.
string
required
The Jinja template string (can be empty to use model’s default)
string
required
JSON-serialized array of chat messages
string
required
JSON-serialized array of tools (can be empty)
bool
required
Whether to add tokens indicating the start of the AI’s response
Returns: string - The formatted prompt
Tokenizer.cs:109-121

Token ID Methods

GetBosTokenId()

Returns the beginning-of-sequence token ID. Returns: int - The BOS token ID
Tokenizer.cs:123-127

GetEosTokenIds()

Returns the end-of-sequence token IDs. Returns: ReadOnlySpan<int> - Span containing EOS token IDs
Tokenizer.cs:129-136

GetPadTokenId()

Returns the padding token ID. Returns: int - The padding token ID
Tokenizer.cs:138-142

Advanced Methods

UpdateOptions(Dictionary<string, string> options)

Updates tokenizer options.
Dictionary<string, string>
required
Dictionary of option names and values
Tokenizer.cs:49-72

CreateStream()

Creates a tokenizer stream for incremental decoding (useful for streaming generation). Returns: TokenizerStream - A tokenizer stream instance
Tokenizer.cs:144-149

Complete Example

Here’s a complete example showing encoding, generation, and decoding:
examples/csharp/ModelChat/Program.cs:44-84

Streaming Example

examples/csharp/ModelChat/Program.cs:200-213

See Also