Transformers.js documentation

tokenizers

You are viewing main version, which requires installation from source. If you'd like regular npm install, checkout the latest stable version (v3.8.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

tokenizers

Tokenizers turn text into the integer ids a model understands, and decode model output back into strings. Use AutoTokenizer.from_pretrained() to load the right implementation for a model ID β€” the class is chosen from the tokenizer’s tokenizer_config.json.

For chat-trained models, tokenizer.apply_chat_template() renders an OpenAI-style message list into the model’s native prompt format.

Classes

AutoTokenizer

Helper class which is used to instantiate pretrained tokenizers with the from_pretrained function. The chosen tokenizer class is determined by the type specified in the tokenizer config.

Example: Create an AutoTokenizer and use it to tokenize a sentence. This will automatically detect the tokenizer type based on the tokenizer class defined in tokenizer_config.json.

import { AutoTokenizer } from '@huggingface/transformers';

const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
const { input_ids } = await tokenizer('I love transformers!');
// Tensor {
//   data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],
//   dims: [1, 6],
//   type: 'int64',
//   size: 6,
// }

AutoTokenizer.from_pretrained(pretrained_model_name_or_path, options)

Instantiate one of the tokenizer classes of the library from a pretrained model.

The tokenizer class to instantiate is selected based on the tokenizer_class property of the config object (either passed as an argument or loaded from pretrained_model_name_or_path if possible)

Parameters

  • pretrained_model_name_or_path (string) β€” The name or path of the pretrained model. Can be either:
    • A string, the model id of a pretrained tokenizer hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like bert-base-uncased, or namespaced under a user or organization name, like dbmdz/bert-base-german-cased.
    • A path to a directory containing tokenizer files, e.g., ./my_model_directory/.
  • options (PretrainedTokenizerOptions) β€” Additional options for loading the tokenizer.

Returns: Promise<PreTrainedTokenizer> β€” The loaded tokenizer.

PreTrainedTokenizer

PreTrainedTokenizer is the base class for all tokenizers in Transformers.js.

PreTrainedTokenizer(text, [options])

Encode/tokenize the given text(s).

Parameters

  • text (string | string[]) β€” The text to tokenize.
  • options (TokenizerCallOptions<string | string[], boolean>) optional β€” Additional tokenization options.

Returns: BatchEncoding<BatchEncodingItem<string | string[], boolean>> β€” Object to be passed to the model.

PreTrainedTokenizer.constructor(tokenizerJSON, tokenizerConfig)

Create a new PreTrainedTokenizer instance.

Parameters

  • tokenizerJSON (Object) β€” The JSON of the tokenizer.
  • tokenizerConfig (Object) β€” The config of the tokenizer.

PreTrainedTokenizer.from_pretrained(pretrained_model_name_or_path, options)

Loads a pretrained tokenizer from the given pretrained_model_name_or_path.

Parameters

  • pretrained_model_name_or_path (string) β€” The path to the pretrained tokenizer.
  • options (PretrainedTokenizerOptions) β€” Additional options for loading the tokenizer.

Returns: Promise<PreTrainedTokenizer> β€” A new instance of the PreTrainedTokenizer class.

Throws

  • Error β€” Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the pretrained_model_name_or_path.

PreTrainedTokenizer.convert_tokens_to_ids(tokens)

Converts a token string (or a sequence of tokens) into a single integer id (or a sequence of ids), using the vocabulary.

Parameters

  • tokens (string | string[]) β€” One or several token(s) to convert to token id(s).

Returns: number | number[] β€” The token id or list of token ids.

PreTrainedTokenizer.tokenize(text, options)

Converts a string into a sequence of tokens.

Parameters

  • text (string) β€” The sequence to be encoded.
  • options (Object) β€” An optional object containing the following properties:
    • pair (string | null) optional β€” A second sequence to be encoded with the first.
    • add_special_tokens (boolean) optional β€” defaults to false β€” Whether or not to add the special tokens associated with the corresponding model.

Returns: string[] β€” The list of tokens.

PreTrainedTokenizer.encode(text, options)

Encodes a single text or a pair of texts using the model’s tokenizer.

Parameters

  • text (string) β€” The text to encode.
  • options (Object) β€” An optional object containing the following properties:
    • text_pair (string | null) optional β€” defaults to null β€” The optional second text to encode.
    • add_special_tokens (boolean) optional β€” defaults to true β€” Whether or not to add the special tokens associated with the corresponding model.
    • return_token_type_ids (boolean | null) optional β€” defaults to null β€” Whether to return token_type_ids.

Returns: number[] β€” An array of token IDs representing the encoded text(s).

PreTrainedTokenizer.batch_decode(batch, decode_args)

Decode a batch of tokenized sequences.

Parameters

  • batch (number[][] | bigint[][] | Tensor) β€” List/Tensor of tokenized input sequences.
  • decode_args (Object) β€” (Optional) Object with decoding arguments.

Returns: string[] β€” List of decoded sequences.

PreTrainedTokenizer.decode(token_ids, [decode_args])

Decodes a sequence of token IDs back to a string.

Parameters

  • token_ids (number[] | bigint[] | Tensor) β€” List/Tensor of token IDs to decode.
  • decode_args (Object) optional β€” defaults to {}
    • skip_special_tokens (boolean) optional β€” defaults to false β€” If true, special tokens are removed from the output string.
    • clean_up_tokenization_spaces (boolean) optional β€” defaults to true β€” If true, spaces before punctuation and abbreviated forms are removed.

Returns: string β€” The decoded string.

Throws

  • Error β€” If token_ids is not a non-empty array of integers.

PreTrainedTokenizer.parse_response(response, options)

Converts an output string created by generating text from a model into a parsed message object. This method is intended for use with chat models, and will read the tokenizer’s response_template to control parsing, unless a response_template option is passed directly.

Accepts either a single sequence or a batch. A single sequence (a string, or a 1D sequence of token ids) returns a single parsed message; a batch (an array of strings, an array of token-id sequences, or a 2D tensor) returns an array of parsed messages, one per item.

Regions with content: "python-call-list" (e.g. [get_weather(city='Paris', days=2)]) are parsed with a strict grammar of keyword-argument calls, without evaluating them; anything else is an error for the region.

Parameters

  • response (string | string[] | number[] | bigint[] | number[][] | bigint[][] | Tensor) β€” The output generated by the model, as decoded text or token ids. This should contain only model output, not any preceding prompt text (that goes in prefix).
  • options (Object)
    • prefix (string | string[] | number[] | bigint[] | number[][] | bigint[][] | Tensor) β€” The prompt that came before generation. This is necessary because many chat templates pre-write part of the message, so we need to see the prompt to parse correctly. For a batched response, pass either a single prefix (broadcast to every item) or one prefix per item. Pass an empty string to opt out.
    • response_template (Object | null) optional β€” defaults to null β€” A response template that indicates the expected output format and how parsing should be performed. Defaults to the tokenizer’s response_template.
    • tools (Object[] | null) optional β€” defaults to null β€” Tools available to the model, in the same format as apply_chat_template accepts. When passed, tool-call arguments are cast using the calling tool’s JSON schema: "7" becomes 7 for an integer parameter but stays "7" for a string one.

Returns: Record<string, any> | Record<string, any>[] β€” A parsed message for a single sequence, or an array of parsed messages for a batch.

Example: Parse a generated response.

const prompt = tokenizer.apply_chat_template(messages, { add_generation_prompt: true, tokenize: false });
// ... generate, then decode the new tokens with `skip_special_tokens: false`
const message = tokenizer.parse_response(generated_text, { prefix: prompt });
// { role: 'assistant', reasoning_content: '...', content: '...' }

PreTrainedTokenizer.get_response_parser(options)

Return a stateful ResponseParser for incrementally parsing a streamed response. Uses the tokenizer’s response_template unless overridden.

prefix (a string, token ids, or 1D tensor) is required: the parser is initialized in the state implied by the chat-prompt context (right-truncated past the template’s start_anchor), so generated chunks passed to parser.feed() are classified correctly even when the chat template emitted assistant-turn content (e.g., <think>\n) that the model continues from. If the stream truly starts from a clean assistant turn, pass prefix: "" to opt out.

The parser emits three event types: { type: 'region_open', field } when a field such as reasoning_content or content starts, { type: 'region_chunk', field, text, dirty } for text written to the open field (dirty marks raw text of structured fields, which is only parsed on close), and { type: 'region_close', field, value } with the field’s parsed value.

Parameters

  • options (Object)
    • prefix (string | number[] | bigint[] | Tensor) β€” The prompt that came before generation.
    • response_template (Object | null) optional β€” defaults to null β€” Template override. Defaults to the tokenizer’s response_template.
    • tools (Object[] | null) optional β€” defaults to null β€” Tools available to the model, in the same format as apply_chat_template accepts. When set, tool-call arguments are cast using the calling tool’s JSON schema as each region closes, so streaming region_close events carry typed arguments.

Returns: ResponseParser

Example: Stream the regions of a generated response.

const prompt = tokenizer.apply_chat_template(messages, { add_generation_prompt: true, tokenize: false });
const parser = tokenizer.get_response_parser({ prefix: prompt });
const handle = (event) => {
    if (event.type === 'region_open') console.log(`[${event.field}]`);
    else if (event.type === 'region_chunk') process.stdout.write(event.text);
    else console.log(`\n[/${event.field}]`, event.value); // 'region_close'
};
// Regions the chat template already opened (e.g., a prefilled `<think>`).
parser.initial_events.forEach(handle);
// Feed decoded text chunks as they are generated, keeping special tokens.
for (const chunk of generated_text_chunks) parser.feed(chunk).forEach(handle);
const [message, final_events] = parser.finalize();
final_events.forEach(handle);
// message: { role: 'assistant', reasoning_content: '...', content: '...' }

PreTrainedTokenizer.decode_single(token_ids, decode_args)

Decode a single list of token ids to a string.

Parameters

  • token_ids (number[] | bigint[]) β€” List of token ids to decode
  • decode_args (Object) β€” Optional arguments for decoding
    • skip_special_tokens (boolean) optional β€” defaults to false β€” Whether to skip special tokens during decoding
    • clean_up_tokenization_spaces (boolean | null) optional β€” defaults to null β€” Whether to clean up tokenization spaces during decoding. If null, the value is set to this.decoder.cleanup if it exists, falling back to this.clean_up_tokenization_spaces if it exists, falling back to true.

Returns: string β€” The decoded string

PreTrainedTokenizer.get_chat_template(options)

Retrieve the chat template string used for tokenizing chat messages. This template is used internally by the apply_chat_template method and can also be used externally to retrieve the model’s chat template for better generation tracking.

Parameters

  • options (Object) β€” An optional object containing the following properties:
    • chat_template (string | null) optional β€” defaults to null β€” A Jinja template or the name of a template to use for this conversion. It is usually not necessary to pass anything to this argument, as the model’s template will be used by default.
    • tools (Object[]) optional β€” defaults to null β€” A list of tools (callable functions) that will be accessible to the model. If the template does not support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, giving the name, description and argument types for the tool. See our chat templating guide for more information.

Returns: string β€” The chat template string.

PreTrainedTokenizer.apply_chat_template(conversation, [options])

Converts a list of message objects with a "role" key and optional content to a list of token ids. This method is intended for use with chat models, and will read the tokenizer’s chat_template attribute to determine the format and control tokens to use when converting.

See the chat templating guide for more information.

Parameters

  • conversation (Message[]) β€” A list of message objects representing the chat history so far.
  • options (ApplyChatTemplateOptions<boolean, boolean, boolean>) optional β€” Options controlling template rendering and tokenization.

Returns: ApplyChatTemplateReturn<boolean, boolean, boolean> β€” The tokenized output.

Example: Applying a chat template to a conversation.

import { AutoTokenizer } from "@huggingface/transformers";

const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1");

const chat = [
  { "role": "user", "content": "Hello, how are you?" },
  { "role": "assistant", "content": "I'm doing great. How can I help you today?" },
  { "role": "user", "content": "I'd like to show off how chat templating works!" },
]

const text = tokenizer.apply_chat_template(chat, { tokenize: false });
// "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"

const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });
// [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]

Type Definitions

PretrainedTokenizerOptions

Type: PretrainedOptions

TextContent

Properties

  • type ('text') β€” The type of content (must be β€˜text’).
  • text (string) β€” The text content.

ImageContent

Properties

  • type ('image') β€” The type of content (must be β€˜image’).

  • image (string | RawImage) optional β€” Optional URL or instance of the image.

    Note: This works for SmolVLM. Qwen2VL and Idefics3 have different implementations.

MessageContent

A single content block inside a chat message. Extend the union to add custom types (e.g. AudioContent) when targeting a specific model.

Type: TextContent | ImageContent | { type: string & {}, [key: string]: any }

ToolCallFunction

Type: { name: string, arguments: Record<string, any>, [key: string]: any }

ToolCall

Type: { type: 'function' | (string & {}), function: ToolCallFunction, [key: string]: any }

Message

Properties

  • role ('user' | 'assistant' | 'system' | string & {}) β€” The role of the message.
  • content (string | MessageContent[]) optional β€” The content of the message. Can be a simple string or an array of content objects.
  • reasoning_content (string) optional β€” Optional reasoning produced by an assistant message.
  • tool_calls (ToolCall[]) optional β€” Optional tool calls produced by an assistant message.

BatchEncodingArrayItem

Type: number[] | number[][]

BatchEncodingItem

Type: Tensor | BatchEncodingArrayItem<string | string[]>

BatchEncoding

The object returned from tokenizer(text). The fields are a Tensor by default, or an Array when return_tensor: false is passed.

Properties

  • input_ids (any) β€” Token ids to be fed to the model.
  • attention_mask (any) β€” Mask indicating which tokens should be attended to (1) versus padded (0).
  • token_type_ids (any) optional β€” Segment ids, present only for tokenizers that distinguish sequence A vs B (e.g. BERT).

TokenizerCallOptions

Options passed to tokenizer(text, options).

Properties

  • text_pair (string | null | string[]) optional β€” defaults to null β€” Optional second sequence to be encoded. Must match the shape of text β€” string when text is a string, array when text is an array.
  • padding (boolean | 'max_length') optional β€” defaults to false β€” Whether to pad the input sequences.
  • add_special_tokens (boolean) optional β€” defaults to true β€” Whether or not to add the special tokens associated with the corresponding model.
  • truncation (boolean | null) optional β€” defaults to null β€” Whether to truncate the input sequences.
  • max_length (number | null) optional β€” defaults to null β€” Maximum length of the returned list and optionally padding length.
  • return_tensor (boolean) optional β€” defaults to true β€” Whether to return the results as Tensors or arrays.
  • return_token_type_ids (boolean | null) optional β€” defaults to null β€” Whether to return the token type ids.

ApplyChatTemplateOptions

Properties

  • chat_template (string | null) optional β€” defaults to null β€” A Jinja template to use for this conversion. If omitted, the model’s chat template is used.
  • tools (Object[] | null) optional β€” defaults to null β€” JSON Schema tool definitions exposed to templates that support function calling. See the chat templating guide.
  • documents (Record<string, string>[] | null) optional β€” defaults to null β€” Documents exposed to templates that support retrieval-augmented generation. See the RAG section of the chat templating guide.
  • add_generation_prompt (boolean) optional β€” defaults to false β€” Whether to end the prompt with the token(s) that indicate the start of an assistant message. The template must support this argument for it to have any effect.
  • tokenize (boolean) optional β€” defaults to true β€” Whether to tokenize the output. If false, the output will be a string.
  • padding (boolean) optional β€” defaults to false β€” Whether to pad sequences to the maximum length. Has no effect if tokenize is false.
  • truncation (boolean) optional β€” defaults to false β€” Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.
  • max_length (number | null) optional β€” defaults to null β€” Maximum length (in tokens) to use for padding or truncation. If omitted, the tokenizer’s max_length is used. Has no effect if tokenize is false.
  • return_tensor (boolean) optional β€” defaults to true β€” Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.
  • return_dict (boolean) optional β€” defaults to true β€” Whether to return a dictionary with named outputs. Has no effect if tokenize is false.
  • tokenizer_kwargs (Object) optional β€” defaults to {} β€” Additional options to pass to the tokenizer.

ApplyChatTemplateReturn

Type: string | BatchEncodingItem<string, boolean> | BatchEncoding<BatchEncodingItem<string, boolean>>

Callbacks

PreTrainedTokenizerCallback

Parameters

Returns: BatchEncoding<BatchEncodingItem<string | string[], boolean>>

Update on GitHub