1
0
mirror of synced 2026-08-31 20:14:59 +00:00
Files

45 lines
1.2 KiB
Ruby
Raw Permalink Normal View History

# frozen_string_literal: true
module DiscourseAi
module Tokenizer
class OpenAiTokenizer < BasicTokenizer
class << self
def tokenizer
@@tokenizer ||= Tiktoken.get_encoding("cl100k_base")
end
def tokenize(text)
tokenizer.encode(text)
end
def encode(text)
tokenizer.encode(text)
end
def decode(token_ids)
tokenizer.decode(token_ids)
end
def truncate(text, max_length)
2024-03-14 17:33:30 -03:00
# fast track common case, /2 to handle unicode chars
# than can take more than 1 token per char
return text if !SiteSetting.ai_strict_token_counting && text.size < max_length / 2
tokenizer.decode(tokenize(text).take(max_length))
rescue Tiktoken::UnicodeError
max_length = max_length - 1
retry
end
2024-10-25 11:51:17 -03:00
def below_limit?(text, limit)
2024-03-14 17:33:30 -03:00
# fast track common case, /2 to handle unicode chars
# than can take more than 1 token per char
2024-10-25 11:51:17 -03:00
return true if !SiteSetting.ai_strict_token_counting && text.size < limit / 2
2024-10-25 11:51:17 -03:00
tokenizer.encode(text).length < limit
end
end
end
end
end