api

package
v0.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2026 License: Apache-2.0 Imports: 6 Imported by: 10

Documentation

Overview

Package api defines the Tokenizer API.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotImplemented = errors.New("not implemented")

Functions

func SpecialTokenStrings added in v0.1.1

func SpecialTokenStrings() []string

SpecialTokenStrings returns a slice of all String values of the enum

Types

type AnnotatedEncoding added in v0.3.5

type AnnotatedEncoding struct {
	IDs               []int       // token IDs
	Spans             []TokenSpan // byte spans for each token (use originalText[span.Start:span.End] to extract)
	SpecialTokensMask []int
}

AnnotatedEncoding contains various optional annotations.

The annotations included are controlled by the options selected with Tokenizer.With.

type Config

type Config struct {
	ConfigFile     string
	TokenizerClass string `json:"tokenizer_class"`

	ChatTemplate           string `json:"chat_template"`
	UseDefaultSystemPrompt bool   `json:"use_default_system_prompt"`

	ModelMaxLength float64        `json:"model_max_length"`
	MaxLength      float64        `json:"max_length"`
	SpModelKwargs  map[string]any `json:"sp_model_kwargs"`

	ClsToken  string `json:"cls_token"`
	UnkToken  string `json:"unk_token"`
	SepToken  string `json:"sep_token"`
	MaskToken string `json:"mask_token"`
	BosToken  string `json:"bos_token"`
	EosToken  string `json:"eos_token"`
	PadToken  string `json:"pad_token"`

	AddBosToken             bool                  `json:"add_bos_token"`
	AddEosToken             bool                  `json:"add_eos_token"`
	AddedTokensDecoder      map[int]TokensDecoder `json:"added_tokens_decoder"`
	AdditionalSpecialTokens []string              `json:"additional_special_tokens"`

	DoLowerCase                bool `json:"do_lower_case"`
	CleanUpTokenizationSpaces  bool `json:"clean_up_tokenization_spaces"`
	SpacesBetweenSpecialTokens bool `json:"spaces_between_special_tokens"`

	TokenizeChineseChars bool   `json:"tokenize_chinese_chars"`
	StripAccents         any    `json:"strip_accents"`
	NameOrPath           string `json:"name_or_path"`
	DoBasicTokenize      bool   `json:"do_basic_tokenize"`
	NeverSplit           any    `json:"never_split"`

	Stride             int    `json:"stride"`
	TruncationSide     string `json:"truncation_side"`
	TruncationStrategy string `json:"truncation_strategy"`
}

Config struct to hold HuggingFace's tokenizer_config.json contents. There is no formal schema for this file, but these are some common fields that may be of use. Specific tokenizer classes are free to implement additional features as they see fit.

The extra field ConfigFile holds the path to the file with the full config.

func ParseConfigContent

func ParseConfigContent(jsonContent []byte) (*Config, error)

ParseConfigContent parses the given json content (of a tokenizer_config.json file) into a Config structure.

func ParseConfigFile

func ParseConfigFile(filePath string) (*Config, error)

ParseConfigFile parses the given file (holding a tokenizer_config.json file) into a Config structure.

type EncodeOptions added in v0.3.5

type EncodeOptions struct {

	// AddSpecialTokens option takes a boolean value, and enables post-processing (e.g., [CLS]/[SEP] for BERT).
	// This is enabled by default for tokenizers that support it, since this is
	// the expected HuggingFace tokenizer behavior.
	AddSpecialTokens bool

	// MaxLen option takes an int value. Set it to a value <= 0 to disable MaxLen.
	// Encoding will be truncated to this length.
	MaxLen int

	// IncludeSpans option takes a boolean, and indicates if EncodeWithAnnotations should include spans.
	IncludeSpans bool

	// IncludeSpecialTokensMask option takes a boolean value, and enables post-processing (e.g., [CLS]/[SEP] for BERT).
	IncludeSpecialTokensMask bool
}

EncodeOptions for the tokenizer.

type SpecialToken

type SpecialToken int

SpecialToken is an enum of commonly used special tokens.

const (
	TokBeginningOfSentence SpecialToken = iota
	TokEndOfSentence
	TokUnknown
	TokPad
	TokMask
	TokClassification
	TokSpecialTokensCount
)

func SpecialTokenString added in v0.1.1

func SpecialTokenString(s string) (SpecialToken, error)

SpecialTokenString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func SpecialTokenValues added in v0.1.1

func SpecialTokenValues() []SpecialToken

SpecialTokenValues returns all values of the enum

func (SpecialToken) IsASpecialToken added in v0.1.1

func (i SpecialToken) IsASpecialToken() bool

IsASpecialToken returns "true" if the value is listed in the enum definition. "false" otherwise

func (SpecialToken) MarshalJSON added in v0.1.1

func (i SpecialToken) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for SpecialToken

func (SpecialToken) MarshalText added in v0.1.1

func (i SpecialToken) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for SpecialToken

func (SpecialToken) MarshalYAML added in v0.1.1

func (i SpecialToken) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for SpecialToken

func (SpecialToken) String added in v0.1.1

func (i SpecialToken) String() string

func (*SpecialToken) UnmarshalJSON added in v0.1.1

func (i *SpecialToken) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for SpecialToken

func (*SpecialToken) UnmarshalText added in v0.1.1

func (i *SpecialToken) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for SpecialToken

func (*SpecialToken) UnmarshalYAML added in v0.1.1

func (i *SpecialToken) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for SpecialToken

func (SpecialToken) Values added in v0.1.1

func (SpecialToken) Values() []string

type TokenSpan added in v0.3.2

type TokenSpan struct {
	Start int // start byte position (inclusive)
	End   int // end byte position (exclusive)
}

TokenSpan represents the byte span of a token in the original text. Start and End are byte offsets (not rune offsets), suitable for slicing Go strings directly: originalText[span.Start:span.End]. This is useful for token classification tasks (NER, chunking) where you need to map token predictions back to positions in the original text.

type Tokenizer

type Tokenizer interface {
	// Encode converts text to token IDs with post-processing (e.g., [CLS]/[SEP]).
	// Equivalent to EncodeWithOptions(text, true).
	Encode(text string) []int

	// EncodeWithAnnotations returns the encoded text along with requested annotations.
	// Use With to select the desired annotation.
	EncodeWithAnnotations(text string) AnnotatedEncoding

	// With applies options to a tokenizer.
	// If an option is unsupported, it returns an ErrNotImplemented derived error.
	//
	// These options may change how the tokenizer behaves, and usually they are set only once.
	// It is up to the caller to coordinate if the tokenizer is being used with alternating
	// options — it’s not a common pattern.
	With(options EncodeOptions) error

	// Decode converts the tokens back to their string representations.
	Decode([]int) string

	// SpecialTokenID returns ID for given special token if registered, or an ErrNotImplemented derived error if not.
	//
	// This allows for a common representation of special tokens across different tokenizers.
	SpecialTokenID(token SpecialToken) (int, error)

	// Normalize returns the normalization used by the tokenizer (e.g.: BERT lower cases the string)
	// If a Tokenizer uses no normalization this simply returns its input.
	Normalize(string) string

	// VocabSize returns the total number of tokens in the vocabulary.
	VocabSize() int

	// Config returns the HuggingFace tokenizer configuration.
	// It is optional, and in case the tokenizer has been instantiated in some other fashion it may return nil.
	Config() *Config
}

Tokenizer interface allows one convert test to "tokens" (integer ids) and back.

It also allows mapping of special tokens: tokens with a common semantic (like padding) but that may map to different ids (int) for different tokenizers.

type TokensDecoder

type TokensDecoder struct {
	Content    string `json:"content"`
	Lstrip     bool   `json:"lstrip"`
	Normalized bool   `json:"normalized"`
	Rstrip     bool   `json:"rstrip"`
	SingleWord bool   `json:"single_word"`
	Special    bool   `json:"special"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL