tokenizer

This commit is contained in:
1iaan
2026-04-03 10:29:38 +08:00
parent de99cb2806
commit c1a895258f
70 changed files with 22320 additions and 239 deletions

11
tokenizer/Dockerfile Normal file
View File

@@ -0,0 +1,11 @@
FROM quay.io/0voice/python:3.10-alpine
WORKDIR /app
ENV PORT 3002
ADD ./tokenizer.py /app
ADD ./requirements.txt /app
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn --upgrade pip
RUN pip install --root-user-action=ignore -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn -r requirements.txt
CMD ["sh","-c","nuxt --port ${PORT} --module tokenizer.py --workers 2"]

6
tokenizer/README.md Normal file
View File

@@ -0,0 +1,6 @@
# tokenizer
## 镜像构建
```
docker build -t tokenizer:1.0.0 .
```

View File

@@ -0,0 +1,2 @@
nuxt>=0.2.0
tiktoken>=0.3.3

65
tokenizer/tokenizer.py Normal file
View File

@@ -0,0 +1,65 @@
from nuxt import route, logger, Request
from nuxt.repositorys.validation import fields, use_args
import traceback
import tiktoken
encoding_cache = {}
support_models = set(["kimi-k2.5",
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-4",
"gpt-4-32k"])
support_model_prefixes = (
"gpt-3.5-turbo-",
"gpt-4-",
"moonshot-",
"kimi-",
)
@route("/tokenizer/<str:model_name>", methods=["POST"])
@use_args({
"role": fields.Str(required=True),
"content": fields.Str(required=True),
"name": fields.Str(required=False)
}, location="json")
def get_num_tokens(req: Request, message: dict, model_name: str):
try:
return {
"code": 200,
"num_tokens": num_tokens_from_messages([message], model=model_name)
}
except Exception as e:
logger.error(traceback.format_exc())
return {
"code": 500,
"msg": "{}".format(e)
}
def num_tokens_from_messages(messages, model="gpt-3.5-turbo"):
"""Returns the number of tokens used by a list of messages."""
encoding = None
if model in encoding_cache:
encoding = encoding_cache.get(model)
else:
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
encoding = tiktoken.get_encoding("cl100k_base")
encoding_cache[model] = encoding
if model in support_models or model.startswith(support_model_prefixes):
num_tokens = 0
for message in messages:
num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
for key, value in message.items():
num_tokens += len(encoding.encode(value))
if key == "name": # if there's a name, the role is omitted
num_tokens += -1 # role is always required and always 1 token
num_tokens += 3 # every reply is primed with <im_start>assistant
return num_tokens
else:
raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")