tokenizer

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 3 Imported by: 79

README

Tests

Tokenizer

This is a pure go port of OpenAI's tokenizer.

Buy Me A Coffee

Usage

package main

import (
    "fmt"
    "github.com/tiktoken-go/tokenizer"
)

func main() {
    enc, err := tokenizer.Get(tokenizer.Cl100kBase)
    if err != nil {
        panic("oh oh")
    }

    // this should print a list of token ids
    ids, _, _ := enc.Encode("supercalifragilistic")
    fmt.Println(ids)

    // this should print the original string back
    text, _ := enc.Decode(ids)
    fmt.Println(text)
}

Alternatively you can use the included command-line tool

> tokenizer -h

Usage of tokenizer:
  -decode string
        tokens to decode
  -encode string
        text to encode
  -token string
        text to calculate token

> tokenizer -encode supercalifragilistic

Todo

  • ✅ port code
  • ✅ o200k_base encoding
  • ✅ cl100k_base encoding
  • ✅ r50k_base encoding
  • ✅ p50k_base encoding
  • ✅ p50k_edit encoding
  • ✅ tests
  • ❌ handle special tokens
  • ❌ gpt-2 model

Caveats

This library embeds OpenAI's vocabularies—which are not small (~4Mb)— as go maps. This is different than what the way python version of tiktoken works, which downloads the dictionaries and puts them in a cache folder.

However, since the dictionaries are compiled during the go build process the performance and start-up times should be better than downloading and loading them at runtime.

Alternatives

Here is a list of other libraries that do something similar.

Documentation

Index

Constants

View Source
const (
	// ErrorModeNone leaves invalid UTF-8 as is: Decode returns the decoded
	// bytes unchanged, so the result may not be valid UTF-8, and Encode
	// tokenizes its input without cleaning it first. This is the default.
	ErrorModeNone = codec.ErrorModeNone

	// ErrorModeReplace replaces each maximal invalid subsequence with a single
	// U+FFFD, matching errors="replace" (tiktoken's default).
	ErrorModeReplace = codec.ErrorModeReplace

	// ErrorModeIgnore drops invalid bytes, matching errors="ignore".
	ErrorModeIgnore = codec.ErrorModeIgnore

	// ErrorModeStrict makes Decode, Encode and Count return an error reporting
	// the byte offset of the first invalid sequence, matching errors="strict".
	ErrorModeStrict = codec.ErrorModeStrict
)

Variables

View Source
var (
	ErrModelNotSupported    = errors.New("model not supported")
	ErrEncodingNotSupported = errors.New("encoding not supported")

	// ErrInvalidUTF8 is returned in ErrorModeStrict when the input to Encode
	// or Count, or the output of Decode, is not valid UTF-8. The error wraps
	// it with the byte offset of the first invalid sequence; use errors.Is.
	ErrInvalidUTF8 = codec.ErrInvalidUTF8
)

Functions

This section is empty.

Types

type Codec

type Codec interface {
	// GetName returns the codec's name (i.e. p50k_base, ...)
	GetName() string

	// Count returns the number of tokens in the input string.
	Count(string) (int, error)

	// Encode returns the token IDs and tokens for the input string.
	Encode(string) ([]uint, []string, error)

	// Decode returns the text represented by the token IDs.
	Decode([]uint) (string, error)

	// ErrorMode returns the codec's current error mode.
	ErrorMode() ErrorMode

	// SetErrorMode sets the codec's behavior when invalid UTF-8 is passed to
	// either Encode or Decode methods
	SetErrorMode(ErrorMode)
}

func ForModel

func ForModel(model Model) (Codec, error)

ForModel returns a new instance of a Codec implementation based on the specified OpenAI model. If the specified model is not supported, an error is returned.

func Get

func Get(encoding Encoding) (Codec, error)

Get returns a new instance of a Codec implementation based on the specified encoding format. The returned Codec instance can be used to encode (tokenize) and decode (reassemble) text. If the specified encoding is not supported, an error is returned.

type Encoding

type Encoding string
const (
	GPT2Enc    Encoding = "gpt2"
	R50kBase   Encoding = "r50k_base"
	P50kBase   Encoding = "p50k_base"
	P50kEdit   Encoding = "p50k_edit"
	Cl100kBase Encoding = "cl100k_base"
	O200kBase  Encoding = "o200k_base"
)

type ErrorMode added in v0.9.0

type ErrorMode = codec.ErrorMode

ErrorMode controls how a codec handles invalid UTF-8: in the bytes produced by Decode, and in the input string passed to Encode and Count. Byte-level BPE tokens can hold part of a multi-byte character, so decoding a slice of token IDs can produce invalid UTF-8. The modes mirror the errors argument of Python's bytes.decode used by tiktoken. Encode applies the same mode to its input before tokenizing, so Encode(s) gives the same IDs as encoding the string Decode would produce for s's bytes.

type Model

type Model string
const (
	O1                       Model = "o1"
	O1Preview                Model = "o1-preview"
	O1Mini                   Model = "o1-mini"
	O3                       Model = "o3"
	O3Mini                   Model = "o3-mini"
	O4Mini                   Model = "o4-mini"
	GPT5                     Model = "gpt-5"
	GPT5Mini                 Model = "gpt-5-mini"
	GPT5Nano                 Model = "gpt-5-nano"
	GPT41                    Model = "gpt-4.1"
	GPT4o                    Model = "gpt-4o"
	GPT4                     Model = "gpt-4"
	GPT35Turbo               Model = "gpt-3.5-turbo"
	GPT35                    Model = "gpt-3.5"
	TextEmbeddingAda002      Model = "text-embedding-ada-002"
	TextDavinci003           Model = "text-davinci-003"
	TextDavinci002           Model = "text-davinci-002"
	CodeDavinci002           Model = "code-davinci-002"
	CodeDavinci001           Model = "code-davinci-001"
	CodeCushman002           Model = "code-cushman-002"
	CodeCushman001           Model = "code-cushman-001"
	DavinciCodex             Model = "davinci-codex"
	CushmanCodex             Model = "cushman-codex"
	TextDavinci001           Model = "text-davinci-001"
	TextCurie001             Model = "text-curie-001"
	TextBabbage001           Model = "text-babbage-001"
	TextAda001               Model = "text-ada-001"
	Davinci                  Model = "davinci"
	Curie                    Model = "curie"
	Babbage                  Model = "babbage"
	Ada                      Model = "ada"
	TextSimilarityDavinci001 Model = "text-similarity-davinci-001"
	TextSimilarityCurie001   Model = "text-similarity-curie-001"
	TextSimilarityBabbage001 Model = "text-similarity-babbage-001"
	TextSimilarityAda001     Model = "text-similarity-ada-001"
	TextSearchDavinciDoc001  Model = "text-search-davinci-doc-001"
	TextSearchCurieDoc001    Model = "text-search-curie-doc-001"
	TextSearchAdaDoc001      Model = "text-search-ada-doc-001"
	TextSearchBabbageDoc001  Model = "text-search-babbage-doc-001"
	CodeSearchBabbageCode001 Model = "code-search-babbage-code-001"
	CodeSearchAdaCode001     Model = "code-search-ada-code-001"
	TextDavinciEdit001       Model = "text-davinci-edit-001"
	CodeDavinciEdit001       Model = "code-davinci-edit-001"
	GPT2                     Model = "gpt2"
)

Directories

Path Synopsis
cmd
tokenizer command
internal
cmd command

Jump to

Keyboard shortcuts

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