2023-04-19 10:55:59 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
2023-05-15 14:10:42 -04:00
|
|
|
module Tokenizer
|
|
|
|
class BasicTokenizer
|
|
|
|
def self.tokenizer
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.tokenize(text)
|
|
|
|
tokenizer.encode(text).tokens
|
|
|
|
end
|
|
|
|
def self.size(text)
|
|
|
|
tokenize(text).size
|
|
|
|
end
|
|
|
|
def self.truncate(text, max_length)
|
|
|
|
tokenizer.decode(tokenizer.encode(text).ids.take(max_length))
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class BertTokenizer < BasicTokenizer
|
|
|
|
def self.tokenizer
|
|
|
|
@@tokenizer ||=
|
|
|
|
Tokenizers.from_file("./plugins/discourse-ai/tokenizers/bert-base-uncased.json")
|
|
|
|
end
|
2023-04-19 10:55:59 -04:00
|
|
|
end
|
|
|
|
|
2023-05-15 14:10:42 -04:00
|
|
|
class AnthropicTokenizer < BasicTokenizer
|
|
|
|
def self.tokenizer
|
|
|
|
@@tokenizer ||=
|
|
|
|
Tokenizers.from_file("./plugins/discourse-ai/tokenizers/claude-v1-tokenization.json")
|
|
|
|
end
|
2023-05-06 06:31:53 -04:00
|
|
|
end
|
2023-05-15 14:10:42 -04:00
|
|
|
|
|
|
|
class OpenAiTokenizer < BasicTokenizer
|
|
|
|
def self.tokenizer
|
|
|
|
@@tokenizer ||= Tiktoken.get_encoding("cl100k_base")
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.tokenize(text)
|
|
|
|
tokenizer.encode(text)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.truncate(text, max_length)
|
|
|
|
tokenizer.decode(tokenize(text).take(max_length))
|
|
|
|
end
|
2023-04-19 10:55:59 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|