GPTEncoder
1.0.4
适用于 OpenAI GPT 模型的 Swift BPE 编码器/解码器。用于对 OpenAI GPT API 文本进行标记的编程接口。
GPT 系列模型使用标记处理文本,标记是文本中常见的字符序列。这些模型了解这些标记之间的统计关系,并且擅长生成标记序列中的下一个标记。
您可以使用下面的工具来了解 API 如何对一段文本进行标记,以及该文本中的标记总数。
该库基于nodeJS gpt-3-encoder和OpenAI官方Python GPT编码器/解码器
我还创建了 GPTTokenizerUI,这是一个 SPM 库,您可以将其集成到您的应用程序中,以提供 GUI 来输入文本并显示 GPT API 使用的标记化结果。
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
标记数组,您只需调用传递字符串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
标记数组解码回String
您可以调用decode
并传递标记数组。
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."
在内部,缓存用于提高对令牌进行编码时的性能,您也可以重置缓存。
encoder . clearCache ( )