This repository was archived by the owner on Jun 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathTikTokensUtil.java
More file actions
302 lines (271 loc) · 8.77 KB
/
TikTokensUtil.java
File metadata and controls
302 lines (271 loc) · 8.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package com.theokanning.openai.utils;
import com.knuddels.jtokkit.Encodings;
import com.knuddels.jtokkit.api.Encoding;
import com.knuddels.jtokkit.api.EncodingRegistry;
import com.knuddels.jtokkit.api.EncodingType;
import com.knuddels.jtokkit.api.ModelType;
import com.theokanning.openai.completion.chat.ChatMessage;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.*;
/**
* Token calculation tool class
*/
public class TikTokensUtil {
/**
* Model name corresponds to Encoding
*/
private static final Map<String, Encoding> modelMap = new HashMap<>();
/**
* Registry instance
*/
private static final EncodingRegistry registry = Encodings.newDefaultEncodingRegistry();
static {
for (ModelType modelType : ModelType.values()) {
modelMap.put(modelType.getName(), registry.getEncodingForModel(modelType));
}
modelMap.put(ModelEnum.GPT_3_5_TURBO_0301.getName(), registry.getEncodingForModel(ModelType.GPT_3_5_TURBO));
modelMap.put(ModelEnum.GPT_4_32K.getName(), registry.getEncodingForModel(ModelType.GPT_4));
modelMap.put(ModelEnum.GPT_4_32K_0314.getName(), registry.getEncodingForModel(ModelType.GPT_4));
modelMap.put(ModelEnum.GPT_4_0314.getName(), registry.getEncodingForModel(ModelType.GPT_4));
modelMap.put(ModelEnum.GPT_4_1106_preview.getName(), registry.getEncodingForModel(ModelType.GPT_4));
}
/**
* Get encoding array through Encoding and text.
*
* @param enc Encoding type
* @param text Text information
* @return Encoding array
*/
public static List<Integer> encode(Encoding enc, String text) {
return isBlank(text) ? new ArrayList<>() : enc.encode(text);
}
/**
* Calculate tokens of text information through Encoding.
*
* @param enc Encoding type
* @param text Text information
* @return Number of tokens
*/
public static int tokens(Encoding enc, String text) {
return encode(enc, text).size();
}
/**
* Reverse calculate text information through Encoding and encoded array
*
* @param enc Encoding
* @param encoded Encoding array
* @return Text information corresponding to the encoding array.
*/
public static String decode(Encoding enc, List<Integer> encoded) {
return enc.decode(encoded);
}
/**
* Get an Encoding object by Encoding type
*
* @param encodingType
* @return Encoding
*/
public static Encoding getEncoding(EncodingType encodingType) {
Encoding enc = registry.getEncoding(encodingType);
return enc;
}
/**
* Obtain the encoding array by encoding;
*
* @param text
* @return Encoding array
*/
public static List<Integer> encode(EncodingType encodingType, String text) {
if (isBlank(text)) {
return new ArrayList<>();
}
Encoding enc = getEncoding(encodingType);
List<Integer> encoded = enc.encode(text);
return encoded;
}
/**
* Compute the tokens of the specified string through EncodingType.
*
* @param encodingType
* @param text
* @return Number of tokens
*/
public static int tokens(EncodingType encodingType, String text) {
return encode(encodingType, text).size();
}
/**
* Reverse the encoded array to get the string text using EncodingType and the encoded array.
*
* @param encodingType
* @param encoded
* @return The string corresponding to the encoding array.
*/
public static String decode(EncodingType encodingType, List<Integer> encoded) {
Encoding enc = getEncoding(encodingType);
return enc.decode(encoded);
}
/**
* Get an Encoding object by model name.
*
* @param modelName
* @return Encoding
*/
public static Encoding getEncoding(String modelName) {
return modelMap.get(modelName);
}
/**
* Get the encoded array by model name using encode.
*
* @param text Text information
* @return Encoding array
*/
public static List<Integer> encode(String modelName, String text) {
if (isBlank(text)) {
return new ArrayList<>();
}
Encoding enc = getEncoding(modelName);
if (Objects.isNull(enc)) {
return new ArrayList<>();
}
List<Integer> encoded = enc.encode(text);
return encoded;
}
/**
* Calculate the tokens of a specified string by model name.
*
* @param modelName
* @param text
* @return Number of tokens
*/
public static int tokens(String modelName, String text) {
return encode(modelName, text).size();
}
/**
* Calculate the encoded array for messages by model name.
* Refer to the official processing logic:
* <a href=https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb>https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb</a>
*
* @param modelName
* @param messages
* @return Number of tokens
*/
public static int tokens(String modelName, List<ChatMessage> messages) {
Encoding encoding = getEncoding(modelName);
int tokensPerMessage = 0;
int tokensPerName = 0;
//3.5统一处理
if (modelName.equals("gpt-3.5-turbo-0301") || modelName.equals("gpt-3.5-turbo")) {
tokensPerMessage = 4;
tokensPerName = -1;
}
//4.0统一处理
if (modelName.equals("gpt-4") || modelName.equals("gpt-4-0314")) {
tokensPerMessage = 3;
tokensPerName = 1;
}
int sum = 0;
for (ChatMessage msg : messages) {
sum += tokensPerMessage;
if(msg.getContent() instanceof String){
sum += tokens(encoding, msg.getContent().toString());
}
sum += tokens(encoding, msg.getRole());
sum += tokens(encoding, msg.getName());
if (isNotBlank(msg.getName())) {
sum += tokensPerName;
}
}
sum += 3;
return sum;
}
/**
* Reverse the string text through the model name and the encoded array.
*
* @param modelName
* @param encoded
* @return
*/
public static String decode(String modelName, List<Integer> encoded) {
Encoding enc = getEncoding(modelName);
return enc.decode(encoded);
}
/**
* Obtain the modelType.
*
* @param name
* @return
*/
public static ModelType getModelTypeByName(String name) {
if (ModelEnum.GPT_3_5_TURBO_0301.getName().equals(name)) {
return ModelType.GPT_3_5_TURBO;
}
if (ModelEnum.GPT_4.getName().equals(name)
|| ModelEnum.GPT_4_32K.getName().equals(name)
|| ModelEnum.GPT_4_32K_0314.getName().equals(name)
|| ModelEnum.GPT_4_0314.getName().equals(name)) {
return ModelType.GPT_4;
}
for (ModelType modelType : ModelType.values()) {
if (modelType.getName().equals(name)) {
return modelType;
}
}
return null;
}
@Getter
@AllArgsConstructor
public enum ModelEnum {
/**
* gpt-3.5-turbo
*/
GPT_3_5_TURBO("gpt-3.5-turbo"),
/**
* Temporary model, not recommended for use.
*/
GPT_3_5_TURBO_0301("gpt-3.5-turbo-0301"),
/**
* GPT4.0
*/
GPT_4("gpt-4"),
/**
* Temporary model, not recommended for use.
*/
GPT_4_0314("gpt-4-0314"),
/**
* GPT4.0 超长上下文
*/
GPT_4_32K("gpt-4-32k"),
/**
* Temporary model, not recommended for use.
*/
GPT_4_32K_0314("gpt-4-32k-0314"),
/**
* Temporary model, not recommended for use.
*/
GPT_4_1106_preview("gpt-4-1106-preview");
private String name;
}
public static boolean isBlankChar(int c) {
return Character.isWhitespace(c) || Character.isSpaceChar(c) || c == 65279 || c == 8234 || c == 0 || c == 12644 || c == 10240 || c == 6158;
}
public static boolean isBlankChar(char c) {
return isBlankChar((int) c);
}
public static boolean isNotBlank(CharSequence str) {
return !isBlank(str);
}
public static boolean isBlank(CharSequence str) {
int length;
if (str != null && (length = str.length()) != 0) {
for (int i = 0; i < length; ++i) {
if (!isBlankChar(str.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
}