OgaTokenizer class provides methods to encode text into token sequences and decode token sequences back into text. It’s essential for preparing input for the model and interpreting the generated output.
Class Definition
~/workspace/source/src/ort_genai.h:301
Methods
Create()
Create a tokenizer instance from a model.const OgaModel&
required
The model to create the tokenizer from
std::unique_ptr<OgaTokenizer> - A unique pointer to the created tokenizer
Example
Encode()
Encode a string into token sequences.const char*
required
The input text to encode
OgaSequences&
required
The sequences object to store the encoded tokens
std::runtime_error if encoding fails
Example
Decode()
Decode token sequences back into text.const int32_t*
required
Pointer to the token data array
size_t
required
Number of tokens in the array
OgaString - The decoded text string
Example
Example with std::span (C++20)
GetBosTokenId()
Get the beginning-of-sequence token ID.int32_t - The BOS token ID
Example
GetEosTokenIds()
Get the end-of-sequence token IDs.Example
GetPadTokenId()
Get the padding token ID.int32_t - The padding token ID
ToTokenId()
Convert a string to its corresponding token ID.const char*
required
The string to convert
int32_t - The token ID for the string
Example
EncodeBatch()
Encode multiple strings in a batch.const char**
required
Array of strings to encode
size_t
required
Number of strings in the array
std::unique_ptr<OgaTensor> - Tensor containing the encoded batch
DecodeBatch()
Decode a batch of token sequences.const OgaTensor&
required
Tensor containing the token sequences to decode
std::unique_ptr<OgaStringArray> - Array of decoded strings
ApplyChatTemplate()
Apply a chat template to format messages.const char*
required
The chat template string (can be nullptr to use default)
const char*
required
JSON string containing the chat messages
const char*
JSON string containing tool definitions (optional)
bool
required
Whether to add the generation prompt
OgaString - The formatted prompt with chat template applied
Example
UpdateOptions()
Update tokenizer options.const char* const*
required
Array of option keys
const char* const*
required
Array of option values
size_t
required
Number of options
Streaming Tokenization
For streaming output, useOgaTokenizerStream to decode tokens one at a time:
OgaTokenizerStream
~/workspace/source/src/ort_genai.h:385
Example
Complete Example
From~/workspace/source/examples/c/src/model_qa.cpp:126:
See Also
- OgaModel - Create models
- OgaGenerator - Generate text
- OgaSequences - Manage token sequences