-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: 修复openai模型在对接其他兼容openai接口平台时获取tokens错误 (#157)
- Loading branch information
1 parent
d214e31
commit 0b083ee
Showing
2 changed files
with
45 additions
and
3 deletions.
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
apps/setting/models_provider/impl/openai_model_provider/model/openai_chat_model.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# coding=utf-8 | ||
""" | ||
@project: maxkb | ||
@Author:虎 | ||
@file: openai_chat_model.py | ||
@date:2024/4/18 15:28 | ||
@desc: | ||
""" | ||
from typing import List | ||
|
||
from langchain_core.messages import BaseMessage, get_buffer_string | ||
from langchain_openai import ChatOpenAI | ||
|
||
|
||
class TokenizerManage: | ||
tokenizer = None | ||
|
||
@staticmethod | ||
def get_tokenizer(): | ||
from transformers import GPT2TokenizerFast | ||
if TokenizerManage.tokenizer is None: | ||
TokenizerManage.tokenizer = GPT2TokenizerFast.from_pretrained('gpt2', | ||
cache_dir="/opt/maxkb/model/tokenizer", | ||
resume_download=False, | ||
force_download=False) | ||
return TokenizerManage.tokenizer | ||
|
||
|
||
class OpenAIChatModel(ChatOpenAI): | ||
def get_num_tokens_from_messages(self, messages: List[BaseMessage]) -> int: | ||
try: | ||
return super().get_num_tokens_from_messages(messages) | ||
except Exception as e: | ||
tokenizer = TokenizerManage.get_tokenizer() | ||
return sum([len(tokenizer.encode(get_buffer_string([m]))) for m in messages]) | ||
|
||
def get_num_tokens(self, text: str) -> int: | ||
try: | ||
return super().get_num_tokens(text) | ||
except Exception as e: | ||
tokenizer = TokenizerManage.get_tokenizer() | ||
return len(tokenizer.encode(text)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters