Update app.py
Browse files
app.py
CHANGED
@@ -75,17 +75,13 @@ def normalize_content(content):
|
|
75 |
# 如果是其他类型,返回空字符串
|
76 |
return ""
|
77 |
|
78 |
-
def calculate_tokens_via_tiktoken(text, model="gpt-
|
79 |
"""
|
80 |
使用 tiktoken 库根据 GPT 模型计算 token 数量。
|
81 |
Claude 模型与 GPT 模型的 token 计算机制类似,因此可以使用 tiktoken。
|
82 |
-
这里我们指定本地的编码文件路径。
|
83 |
"""
|
84 |
-
#
|
85 |
-
|
86 |
-
|
87 |
-
# 打开本地编码文件
|
88 |
-
encoding = tiktoken.Encoding.open(encoding_path)
|
89 |
|
90 |
# 对文本进行 tokenization
|
91 |
tokens = encoding.encode(text)
|
@@ -128,7 +124,7 @@ def messages():
|
|
128 |
previous_messages = "\n\n".join([normalize_content(msg['content']) for msg in json_body['messages']])
|
129 |
|
130 |
# 动态计算输入的 token 数量,使用 tiktoken 进行 tokenization
|
131 |
-
input_tokens = calculate_tokens_via_tiktoken(previous_messages, model="gpt-
|
132 |
|
133 |
msg_id = str(uuid.uuid4())
|
134 |
response_event = Event()
|
@@ -231,7 +227,7 @@ def messages():
|
|
231 |
sio.disconnect()
|
232 |
|
233 |
# 动态计算输出的 token 数量,使用 tiktoken 进行 tokenization
|
234 |
-
output_tokens = calculate_tokens_via_tiktoken(''.join(response_text), model="gpt-
|
235 |
|
236 |
yield create_event("content_block_stop", {"type": "content_block_stop", "index": 0})
|
237 |
yield create_event("message_delta", {
|
@@ -306,7 +302,7 @@ def handle_non_stream(previous_messages, msg_id, model, input_tokens):
|
|
306 |
response_event.wait(timeout=30)
|
307 |
|
308 |
# 动态计算输出的 token 数量,使用 tiktoken 进行 tokenization
|
309 |
-
output_tokens = calculate_tokens_via_tiktoken(''.join(response_text), model="gpt-
|
310 |
|
311 |
# 生成完整的响应
|
312 |
full_response = {
|
|
|
75 |
# 如果是其他类型,返回空字符串
|
76 |
return ""
|
77 |
|
78 |
+
def calculate_tokens_via_tiktoken(text, model="gpt-3.5-turbo"):
|
79 |
"""
|
80 |
使用 tiktoken 库根据 GPT 模型计算 token 数量。
|
81 |
Claude 模型与 GPT 模型的 token 计算机制类似,因此可以使用 tiktoken。
|
|
|
82 |
"""
|
83 |
+
# 获取模型的编码器
|
84 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
|
|
|
|
|
|
85 |
|
86 |
# 对文本进行 tokenization
|
87 |
tokens = encoding.encode(text)
|
|
|
124 |
previous_messages = "\n\n".join([normalize_content(msg['content']) for msg in json_body['messages']])
|
125 |
|
126 |
# 动态计算输入的 token 数量,使用 tiktoken 进行 tokenization
|
127 |
+
input_tokens = calculate_tokens_via_tiktoken(previous_messages, model="gpt-3.5-turbo")
|
128 |
|
129 |
msg_id = str(uuid.uuid4())
|
130 |
response_event = Event()
|
|
|
227 |
sio.disconnect()
|
228 |
|
229 |
# 动态计算输出的 token 数量,使用 tiktoken 进行 tokenization
|
230 |
+
output_tokens = calculate_tokens_via_tiktoken(''.join(response_text), model="gpt-3.5-turbo")
|
231 |
|
232 |
yield create_event("content_block_stop", {"type": "content_block_stop", "index": 0})
|
233 |
yield create_event("message_delta", {
|
|
|
302 |
response_event.wait(timeout=30)
|
303 |
|
304 |
# 动态计算输出的 token 数量,使用 tiktoken 进行 tokenization
|
305 |
+
output_tokens = calculate_tokens_via_tiktoken(''.join(response_text), model="gpt-3.5-turbo")
|
306 |
|
307 |
# 生成完整的响应
|
308 |
full_response = {
|