| 1 | # tiktoken-go |
| 2 | Go 语言版本的 OpenAI 的 tiktoken。 |
| 3 | 帮你把文本转换成 OpenAI 的模型可以识别的 token。 |
| 4 | tiktoken的原项目地址[tiktoken](https://github.com/openai/tiktoken). |
| 5 | |
| 6 | # 用法 |
| 7 | |
| 8 | ## 安装 |
| 9 | |
| 10 | ```bash |
| 11 | go get github.com/pkoukk/tiktoken-go |
| 12 | ``` |
| 13 | ## 缓存 |
| 14 | Tiktoken-go 和原始的 Tiktoken 库一样,具有相同的缓存机制。 |
| 15 | |
| 16 | 您可以使用环境变量 TIKTOKEN_CACHE_DIR 来设置缓存目录。 |
| 17 | |
| 18 | 一旦设置了该变量,tiktoken-go 将使用该目录来缓存令牌字典。 |
| 19 | |
| 20 | 如果您未设置此环境变量,则 tiktoken-go 将在每次首次初始化编码时下载字典。 |
| 21 | |
| 22 | |
| 23 | ## 替代 BPE 加载器 |
| 24 | 默认情况下,tiktoken-go 会在运行时下载字典,如果您不想使用缓存或每次下载字典,您可以使用替代 BPE 加载器。 |
| 25 | |
| 26 | 只需在调用 `tiktoken.GetEncoding` 或 `tiktoken.EncodingForModel` 之前调用 `tiktoken.SetBpeLoader`。 |
| 27 | |
| 28 | `BpeLoader` 是一个接口,您可以通过实现此接口来实现自己的 BPE 加载器。 |
| 29 | |
| 30 | ### 离线 BPE 加载器 |
| 31 | 离线 BPE 加载器从嵌入文件加载 BPE 字典。 |
| 32 | |
| 33 | 由于 BPE 字典的文件较大,不适合包含在本项目中,故此加载器在其他项目中。 |
| 34 | |
| 35 | 如果需要使用,请引用:[tiktoken_loader](https://github.com/pkoukk/tiktoken-go-loader) |
| 36 | |
| 37 | ## 例子 |
| 38 | |
| 39 | ### Get Token By Encoding |
| 40 | |
| 41 | ```go |
| 42 | package main |
| 43 | |
| 44 | import ( |
| 45 | "fmt" |
| 46 | "github.com/pkoukk/tiktoken-go" |
| 47 | ) |
| 48 | |
| 49 | func main() { |
| 50 | text := "Hello, world!" |
| 51 | encoding := "cl100k_base" |
| 52 | |
| 53 | // 如果你不想在运行时下载字典,你可以使用离线加载器 |
| 54 | // tiktoken.SetBpeLoader(tiktoken_loader.NewOfflineLoader()) |
| 55 | tke, err := tiktoken.GetEncoding(encoding) |
| 56 | if err != nil { |
| 57 | err = fmt.Errorf("getEncoding: %v", err) |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | // encode |
| 62 | token := tke.Encode(text, nil, nil) |
| 63 | |
| 64 | //tokens |
| 65 | fmt.Println((token)) |
| 66 | // num_tokens |
| 67 | fmt.Println(len(token)) |
| 68 | } |
| 69 | ``` |
| 70 | |
| 71 | ### get token by Model |
| 72 | |
| 73 | ```go |
| 74 | package main |
| 75 | |
| 76 | import ( |
| 77 | "fmt" |
| 78 | "github.com/pkoukk/tiktoken-go" |
| 79 | ) |
| 80 | |
| 81 | func main() { |
| 82 | text := "Hello, world!" |
| 83 | encoding := "gpt-3.5-turbo" |
| 84 | |
| 85 | tkm, err := tiktoken.EncodingForModel(encoding) |
| 86 | if err != nil { |
| 87 | err = fmt.Errorf("getEncoding: %v", err) |
| 88 | return |
| 89 | } |
| 90 | |
| 91 | // encode |
| 92 | token := tkm.Encode(text, nil, nil) |
| 93 | |
| 94 | // tokens |
| 95 | fmt.Println(token) |
| 96 | // num_tokens |
| 97 | fmt.Println(len(token)) |
| 98 | } |
| 99 | ``` |
| 100 | |
| 101 | ### 计算chat API消息当中的token消耗 |
| 102 | 这段代码根据[官方示例](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb)编写 |
| 103 | |
| 104 | 编写时间: `2023-06-28` |
| 105 | |
| 106 | 请注意,消息的token计算方式可能随时会发生改变,以下代码并不一定在将来适用,如果您需要精确的计算,请关注官方文档。 |
| 107 | |
| 108 | 如果您发现这段代码不再适用,欢迎您提PR或Issue。 |
| 109 | |
| 110 | ```go |
| 111 | package main |
| 112 | |
| 113 | import ( |
| 114 | "fmt" |
| 115 | |
| 116 | "github.com/pkoukk/tiktoken-go" |
| 117 | "github.com/sashabaranov/go-openai" |
| 118 | ) |
| 119 | |
| 120 | func NumTokensFromMessages(messages []openai.ChatCompletionMessage, model string) (numTokens int) { |
| 121 | tkm, err := tiktoken.EncodingForModel(model) |
| 122 | if err != nil { |
| 123 | err = fmt.Errorf("encoding for model: %v", err) |
| 124 | log.Println(err) |
| 125 | return |
| 126 | } |
| 127 | |
| 128 | var tokensPerMessage, tokensPerName int |
| 129 | switch model { |
| 130 | case "gpt-3.5-turbo-0613", |
| 131 | "gpt-3.5-turbo-16k-0613", |
| 132 | "gpt-4-0314", |
| 133 | "gpt-4-32k-0314", |
| 134 | "gpt-4-0613", |
| 135 | "gpt-4-32k-0613": |
| 136 | tokensPerMessage = 3 |
| 137 | tokensPerName = 1 |
| 138 | case "gpt-3.5-turbo-0301": |
| 139 | tokensPerMessage = 4 // every message follows <|start|>{role/name}\n{content}<|end|>\n |
| 140 | tokensPerName = -1 // if there's a name, the role is omitted |
| 141 | default: |
| 142 | if strings.Contains(model, "gpt-3.5-turbo") { |
| 143 | log.Println("warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.") |
| 144 | return NumTokensFromMessages(messages, "gpt-3.5-turbo-0613") |
| 145 | } else if strings.Contains(model, "gpt-4") { |
| 146 | log.Println("warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.") |
| 147 | return NumTokensFromMessages(messages, "gpt-4-0613") |
| 148 | } else { |
| 149 | err = fmt.Errorf("num_tokens_from_messages() is not implemented for model %s. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.", model) |
| 150 | log.Println(err) |
| 151 | return |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | for _, message := range messages { |
| 156 | numTokens += tokensPerMessage |
| 157 | numTokens += len(tkm.Encode(message.Content, nil, nil)) |
| 158 | numTokens += len(tkm.Encode(message.Role, nil, nil)) |
| 159 | numTokens += len(tkm.Encode(message.Name, nil, nil)) |
| 160 | if message.Name != "" { |
| 161 | numTokens += tokensPerName |
| 162 | } |
| 163 | } |
| 164 | numTokens += 3 // every reply is primed with <|start|>assistant<|message|> |
| 165 | return numTokens |
| 166 | } |
| 167 | ``` |
| 168 | |
| 169 | # available encodings |
| 170 | | Encoding name | OpenAI models | |
| 171 | | ----------------------- | ---------------------------------------------------- | |
| 172 | | `o200k_base` | `gpt-4o` | |
| 173 | | `cl100k_base` | `gpt-4`, `gpt-3.5-turbo`, `text-embedding-ada-002`, `text-embedding-3-small`, `text-embedding-3-large` | |
| 174 | | `p50k_base` | Codex models, `text-davinci-002`, `text-davinci-003` | |
| 175 | | `r50k_base` (or `gpt2`) | GPT-3 models like `davinci` | |
| 176 | |
| 177 | |
| 178 | # available models |
| 179 | | Model name | OpenAI models | |
| 180 | | ---------------------------- | ------------- | |
| 181 | | gpt-4o-* | o200k_base | |
| 182 | | gpt-4 | cl100k_base | |
| 183 | | gpt-4-* | cl100k_base | |
| 184 | | gpt-3.5-turbo | cl100k_base | |
| 185 | | gpt-3.5-turbo-* | cl100k_base | |
| 186 | | text-davinci-003 | p50k_base | |
| 187 | | text-davinci-002 | p50k_base | |
| 188 | | text-davinci-001 | r50k_base | |
| 189 | | text-curie-001 | r50k_base | |
| 190 | | text-babbage-001 | r50k_base | |
| 191 | | text-ada-001 | r50k_base | |
| 192 | | davinci | r50k_base | |
| 193 | | curie | r50k_base | |
| 194 | | babbage | r50k_base | |
| 195 | | ada | r50k_base | |
| 196 | | code-davinci-002 | p50k_base | |
| 197 | | code-davinci-001 | p50k_base | |
| 198 | | code-cushman-002 | p50k_base | |
| 199 | | code-cushman-001 | p50k_base | |
| 200 | | davinci-codex | p50k_base | |
| 201 | | cushman-codex | p50k_base | |
| 202 | | text-davinci-edit-001 | p50k_edit | |
| 203 | | code-davinci-edit-001 | p50k_edit | |
| 204 | | text-embedding-ada-002 | cl100k_base | |
| 205 | | text-embedding-3-small | cl100k_base | |
| 206 | | text-embedding-3-large | cl100k_base | |
| 207 | | text-similarity-davinci-001 | r50k_base | |
| 208 | | text-similarity-curie-001 | r50k_base | |
| 209 | | text-similarity-babbage-001 | r50k_base | |
| 210 | | text-similarity-ada-001 | r50k_base | |
| 211 | | text-search-davinci-doc-001 | r50k_base | |
| 212 | | text-search-curie-doc-001 | r50k_base | |
| 213 | | text-search-babbage-doc-001 | r50k_base | |
| 214 | | text-search-ada-doc-001 | r50k_base | |
| 215 | | code-search-babbage-code-001 | r50k_base | |
| 216 | | code-search-ada-code-001 | r50k_base | |
| 217 | | gpt2 | gpt2 | |
| 218 | |
| 219 | # 与官方 [tiktoken](https://github.com/openai/tiktoken) 的对比 |
| 220 | |
| 221 | ## get token by encoding |
| 222 | [测试结果](./doc/test_result.md#encoding-test-result) |
| 223 | |
| 224 | ## get token by model |
| 225 | [测试结果](./doc/test_result.md#model-test-result) |
| 226 | |
| 227 | # Benchmark |
| 228 | > 你可以使用 [test](./test) 目录下的文件执行基准测试。 |
| 229 | |
| 230 | ## Benchmark result |
| 231 | | name | time/op | os | cpu | text | times | |
| 232 | | ----------- | ------- | ---------- | -------- | -------------------------------- | ------ | |
| 233 | | tiktoken-go | 8795ns | macOS 13.2 | Apple M1 | [UDHR](https://unicode.org/udhr) | 100000 | |
| 234 | | tiktoken | 8838ns | macOS 13.2 | Apple M1 | [UDHR](https://unicode.org/udhr) | 100000 | |
| 235 | |
| 236 | 看上去tiktoken-go的性能基本与原tiktoken一致。 |
| 237 | |
| 238 | 也许在不同的机器上的测试结果会有所不同。也可能是我的测试方法并不恰当。 |
| 239 | |
| 240 | 如果你有更好的测试方法,或者说你想添加在你机器上的测试结果,欢迎提PR。 |
| 241 | |
| 242 | 新的 `o200k_base` 编码, 看起来比 `cl100k_base` 慢. 在以下硬件上,tiktoken-go 比 tiktoken 略慢。 |
| 243 | |
| 244 | | name | encoding | time/op | os | cpu | text | times | |
| 245 | | ----------- | ------- | ------- | ---------- | -------- | -------------------------------- | ------ | |
| 246 | | tiktoken-go | o200k_base | 108522 ns | Ubuntu 22.04 | AMD Ryzen 9 5900HS | [UDHR](http://research.ics.aalto.fi/cog/data/udhr/) | 100000 | |
| 247 | | tiktoken | o200k_base | 70198 ns | Ubuntu 22.04 | AMD Ryzen 9 5900HS | [UDHR](http://research.ics.aalto.fi/cog/data/udhr/) | 100000 | |
| 248 | | tiktoken-go | cl100k_base | 94502 ns | Ubuntu 22.04 | AMD Ryzen 9 5900HS | [UDHR](http://research.ics.aalto.fi/cog/data/udhr/) | 100000 | |
| 249 | | tiktoken | cl100k_base | 54642 ns | Ubuntu 22.04 | AMD Ryzen 9 5900HS | [UDHR](http://research.ics.aalto.fi/cog/data/udhr/) | 100000 | |
| 250 | |
| 251 | # License |
| 252 | [MIT](./LICENSE) |