GPTEncoder

Alt text

用于 OpenAI GPT 模型的 Swift BPE 编码器/解码器。用于 OpenAI GPT API 的文本 Token 化的程序化接口。

GPT 系列模型使用 Token 处理文本,Token 是文本中常见的字符序列。 这些模型理解这些 Token 之间的统计关系,并且擅长生成 Token 序列中的下一个 Token。

您可以使用下面的工具来了解一段文本将被 API 如何 Token 化,以及该段文本中的 Token 总数。

该库基于 nodeJS gpt-3-encoderOpenAI 官方 Python GPT 编码器/解码器

我还创建了 GPTTokenizerUI,一个 SPM 库,您可以将其集成到您的应用程序中,以提供 GUI 来输入文本并显示 GPT API 使用的 Token 化结果。

Alt text

支持的平台

安装

Swift Package Manager

Cocoapods

platform :ios, '15.0'
use_frameworks!

target 'MyApp' do
  pod 'GPTEncoder', '~> 1.0.3'
end

用法

let encoder = SwiftGPTEncoder()

let str = "The GPT family of models process text using tokens, which are common sequences of characters found in text."
let encoded = encoder.encode(text: str)
print("String: \(str)")
print("Encoded this string looks like: \(encoded)")
print("Total number of token(s): \(encoded.count) and character(s): \(str.count)")

print("We can look at each token and what it represents")
encoded.forEach { print("Token: \(encoder.decode(tokens: [$0]))") }
print(encoded)

let decoded = encoder.decode(tokens: encoded)
print("We can decode it back into:\n\(decoded)")

编码

要将一个 String 编码成 Int 类型的 Token 数组,您可以简单地调用 encode 并传入该字符串。

let encoded = encoder.encode(text: "The GPT family of models process text using tokens, which are common sequences of characters found in text.")
// Output: [464, 402, 11571, 1641, 286, 4981, 1429, 2420, 1262, 16326, 11, 543, 389, 2219, 16311, 286, 3435, 1043, 287, 2420, 13]

解码

要将一个 Int 类型的 Token 数组解码回 String,您可以调用 decode 并传入该 Token 数组。

let decoded = encoder.decode(tokens: [464, 402, 11571, 1641, 286, 4981, 1429, 2420, 1262, 16326, 11, 543, 389, 2219, 16311, 286, 3435, 1043, 287, 2420, 13])
// Output: "The GPT family of models process text using tokens, which are common sequences of characters found in text."

清除缓存

在内部,使用缓存来提高 Token 编码时的性能,您也可以重置缓存。

encoder.clearCache()