-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: VLLM supplier recalculates token function #2375
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,11 @@ | ||
# coding=utf-8 | ||
|
||
from typing import Dict | ||
from typing import Dict, List | ||
from urllib.parse import urlparse, ParseResult | ||
|
||
from langchain_core.messages import BaseMessage, get_buffer_string | ||
|
||
from common.config.tokenizer_manage_config import TokenizerManage | ||
from setting.models_provider.base_model_provider import MaxKBBaseModel | ||
from setting.models_provider.impl.base_chat_open_ai import BaseChatOpenAI | ||
|
||
|
@@ -33,3 +36,15 @@ def new_instance(model_type, model_name, model_credential: Dict[str, object], ** | |
stream_usage=True, | ||
) | ||
return vllm_chat_open_ai | ||
|
||
def get_num_tokens_from_messages(self, messages: List[BaseMessage]) -> int: | ||
if self.usage_metadata is None or self.usage_metadata == {}: | ||
tokenizer = TokenizerManage.get_tokenizer() | ||
return sum([len(tokenizer.encode(get_buffer_string([m]))) for m in messages]) | ||
return self.usage_metadata.get('input_tokens', 0) | ||
|
||
def get_num_tokens(self, text: str) -> int: | ||
if self.usage_metadata is None or self.usage_metadata == {}: | ||
tokenizer = TokenizerManage.get_tokenizer() | ||
return len(tokenizer.encode(text)) | ||
return self.get_last_generation_info().get('output_tokens', 0) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The provided code has several improvements and fixes, which I will point out: Improvements:
Fixes:
Optimization Suggestions:
Here's the revised and optimized version of the code: @@ -1,7 +1,19 @@
# coding=utf-8
-from typing import Dict
+from typing import Dict, List, Union
from urllib.parse import urlparse, ParseResult
+from langchain_core.messages import BaseMessage, get_buffer_string
+from common.config.tokenizer_manage_config import TokenizerManage
from setting.models_provider.base_model_provider import MaxKBBaseModel
from setting.models_provider.impl.base_chat_open_ai import BaseChatOpenAI
+# Define union type for usage metadata items
+UsageMetadataItem = Union[int, None]
+
@@ -40,9 +56,14 @@ class YourClass(...):
def __init__(self, ..., meta=None):
super().__init__(...)
self.usage_metadata = meta
@staticmethod
+ def _update_usage_metadata(messages, response_dict):
+ tokenizer = TokenizerManage.get_tokenizer()
+ input_length = sum([len(tokenizer.encode(get_buffer_string([m]))) for m in messages])
+ output_length = response_dict.get('output_tokens', 0)
+ return {'input_tokens': input_length, 'output_tokens': output_length}
def generate(self, prompts: List[str]) -> List[Any]:
res = []
prompt_input = '\n'.join(prompts)
- response = ...
+ response = ...
+ response_dict = self._update_usage_metadata(prompts, response)
+ # Update usage metadata (if not already present)
if self.usage_metadata is None:
self.usage_metadata = response_dict
res.append(response)
... This revised version introduces a utility method |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided code has a few areas that can be improved for better readability, efficiency, and maintainability:
Duplicated Import: The
TokenizerManage
class is imported twice. You should only need it once.Unused Variable: In
get_num_tokens
method, there's an unnecessary check where you compare with{}
instead ofNone
.Method Documentation:
Optimization:
Here’s the revised code with these improvements:
Key Enhancements:
common.config.tokenizer_manage_config
.get_num_tokens
.