tokenizer

package
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package tokenizer provides a fast, pure-Go token counter.

It embeds the OpenAI cl100k_base and o200k_base vocabularies and implements byte-level BPE scoring, so token counts are deterministic and require no network calls.

Index

Constants

View Source
const (
	CL100KBase = "cl100k_base"
	O200KBase  = "o200k_base"
)

Encoding names, matching tiktoken's own naming.

Variables

This section is empty.

Functions

func CountForModel added in v1.1.2

func CountForModel(model, s string) (count int, exact bool)

CountForModel counts tokens in s using the tokenizer appropriate for model. exact is false when model has no known BPE vocabulary and the count is an approximation from cl100k_base.

Types

type BPE

type BPE struct {
	// contains filtered or unexported fields
}

BPE is a byte-level byte-pair encoding tokenizer.

var CL100K *BPE

CL100K and O200K are the two embedded vocabularies. CL100K covers the GPT-3.5/GPT-4 era; O200K covers GPT-4o, GPT-4.1, the o-series, and GPT-5.

var Encoder *BPE

Encoder is a ready-to-use byte-level BPE tokenizer for the cl100k_base vocabulary (GPT-3.5/GPT-4 era). Kept for backward compatibility; prefer ForModel for model-accurate counting.

var O200K *BPE

func ForModel added in v1.1.2

func ForModel(model string) (b *BPE, encoding string, exact bool)

ForModel returns the BPE encoder and encoding name for model, and whether that encoding is a confirmed match. OpenAI models resolve exactly; every other model (Claude, Gemini, local models, etc.) has no published public BPE vocabulary, so it falls back to cl100k_base as an approximation and exact is false.

func Load

func Load(fs embed.FS, path string) (*BPE, error)

Load builds a BPE from an embedded tiktoken vocabulary file at path.

Each line is "<base64-token-bytes> <rank>". Tokens are decoded back to raw bytes so both lookup and BPE merges operate on the true token text.

func (*BPE) Count

func (b *BPE) Count(s string) int

Count returns the number of tokens in s.

func (*BPE) Encode

func (b *BPE) Encode(s string) []int

Encode returns the token IDs for s.

Jump to

Keyboard shortcuts

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