tiktoken-go/tokenizer

repository·main·Indexed 19 days ago

https://github.com/tiktoken-go/tokenizer

A pure Go port of OpenAI's tokenizer for high-performance encoding and decoding of text into tokens. It embeds OpenAI's vocabularies directly into the binary as Go maps for faster startup and performance. The library provides a Codec interface to retrieve tokenizers via specific encoding formats (e.g., Cl100kBase, O200kBase) or OpenAI model names (e.g., GPT4, O1). It also includes a CLI tool for encoding, decoding, and listing supported models and encodings.

Tokens
3.3K
Snippets
11
Records
13
Agent score
66%

What's inside tiktoken-go/tokenizer

  1. Understand tokenizer vocabulary embedding

    main
    Unlike the Python version of tiktoken which downloads and caches dictionaries at runtime, this Go implementation embeds OpenAI's vocabularies (approximately 4MB) directly into the binary as Go maps. This occurs during the Go build process, which results in better performance and faster startup times compared to runtime downloading and loading.
  2. Use the tokenizer in Go

    main

    To use the tokenizer in your Go application, use tokenizer.Get() to retrieve an encoding instance (e.g., tokenizer.Cl100kBase). Once you have an encoding instance, you can use .Encode(text) to convert a string into a slice of token IDs, and .Decode(ids) to convert token IDs back into a string.

    Note that Encode returns three values: the slice of IDs, a slice of special tokens (if any), and an error. Decode returns the decoded string and an error.

    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)
    }
  3. Reference the tokenizer CLI flags

    main

    The tokenizer CLI tool supports the following flags:

    • -decode string: tokens to decode
    • -encode string: text to encode
    • -token string: text to calculate token
    Usage of tokenizer:
      -decode string
            tokens to decode
      -encode string
            text to encode
      -token string
            text to calculate token
  4. Complete usage example for encoding and decoding

    main

    This example demonstrates the full workflow: obtaining a tokenizer via Get, encoding a string into token IDs, and decoding those IDs back into the original text.

    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)
    }
  5. Get a Codec by OpenAI model name

    main

    Use tokenizer.ForModel(model Model) to retrieve the correct Codec for a specific OpenAI model. This abstracts away the underlying encoding format used by that model.

    Supported Model examples include:

    • O1, O1Preview, O1Mini, O3, O3Mini, O4Mini (use O200kBase)
    • GPT4, GPT35, GPT35Turbo, TextEmbeddingAda002 (use Cl100kBase)
    • TextDavinci003, CodeDavinci001, etc. (use P50kBase)
    • GPT2 (use GPT2Enc)
    enc, err := tokenizer.ForModel(tokenizer.GPT4o)
    if err != nil {
        // handle error
    }
  6. Get a Codec by encoding format

    main

    Use tokenizer.Get(encoding Encoding) to retrieve a Codec implementation for a specific encoding scheme. This is useful if you know the exact encoding format required (e.g., Cl100kBase).

    Supported Encoding values:

    • O200kBase
    • Cl100kBase
    • R50kBase
    • P50kBase
    • P50kEdit
    • GPT2Enc (via GPT2 model mapping)
    enc, err := tokenizer.Get(tokenizer.Cl100kBase)
    if err != nil {
        // handle error
    }
  7. Encode and decode text using the Codec interface

    main

    The Codec interface is the primary way to interact with tokenizers in this package. It allows you to convert strings to token IDs (encoding) and convert token IDs back into strings (decoding). You can also use it to count the number of tokens in a string without performing a full encoding.

    // Example of using a Codec instance
    ids, tokens, err := enc.Encode("hello world")
    text, err := enc.Decode(ids)
    count, err := enc.Count("hello world")
  8. Reference: tokenizer CLI flags

    main

    The following flags are available for the tokenizer CLI tool:

    FlagTypeDescription
    -modelstringThe target OpenAI model to generate tokens for (default: gpt-3.5-turbo)
    -encodingstringThe encoding format (e.g., cl100k_base)
    -encodestringText to encode
    -decodestringSpace separated list of token ids to decode
    -tokensboolIf true, output the tokens instead of the token ids
    -list-modelsboolList all supported models
    -list-encodingsboolList all supported encoding formats
  9. Reference: Supported Encoding formats

    main

    The following encoding formats are explicitly supported by the Get function:

    const (
    	GPT2Enc    Encoding = "gpt2"
    	R50kBase   Encoding = "r50k_base"
    	P50kBase   Encoding = "p50k_base"
    	P50kEdit   Encoding = "p50k_edit"
    	Cl100kBase Encoding = "cl100k_base"
    	O200kBase  Encoding = "o200k_base"
    )
  10. Reference: Supported OpenAI Models

    main

    The following model names can be passed to ForModel to retrieve the appropriate tokenizer:

    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"
    	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"
    )