token_calculator.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import decimal
  2. from typing import Optional
  3. import tiktoken
  4. from core.constant import llm_constant
  5. class TokenCalculator:
  6. @classmethod
  7. def get_num_tokens(cls, model_name: str, text: str):
  8. if len(text) == 0:
  9. return 0
  10. enc = tiktoken.encoding_for_model(model_name)
  11. tokenized_text = enc.encode(text)
  12. # calculate the number of tokens in the encoded text
  13. return len(tokenized_text)
  14. @classmethod
  15. def get_token_price(cls, model_name: str, tokens: int, text_type: Optional[str] = None) -> decimal.Decimal:
  16. if model_name in llm_constant.models_by_mode['embedding']:
  17. unit_price = llm_constant.model_prices[model_name]['usage']
  18. elif text_type == 'prompt':
  19. unit_price = llm_constant.model_prices[model_name]['prompt']
  20. elif text_type == 'completion':
  21. unit_price = llm_constant.model_prices[model_name]['completion']
  22. else:
  23. raise Exception('Invalid text type')
  24. tokens_per_1k = (decimal.Decimal(tokens) / 1000).quantize(decimal.Decimal('0.001'),
  25. rounding=decimal.ROUND_HALF_UP)
  26. total_price = tokens_per_1k * unit_price
  27. return total_price.quantize(decimal.Decimal('0.0000001'), rounding=decimal.ROUND_HALF_UP)
  28. @classmethod
  29. def get_currency(cls, model_name: str):
  30. return llm_constant.model_currency