Skip to content
Kward Search API index

Class: Kward::TiktokenTokenCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/model/context_usage.rb

Overview

Structured context usage result returned to frontends.

Instance Method Summary collapse

Constructor Details

#initializeTiktokenTokenCounter

Returns a new instance of TiktokenTokenCounter.



83
84
85
# File 'lib/kward/model/context_usage.rb', line 83

def initialize
  @encodings = {}
end

Instance Method Details

#count(text, model:) ⇒ Object



87
88
89
90
91
92
93
94
95
# File 'lib/kward/model/context_usage.rb', line 87

def count(text, model:)
  text = text.to_s
  tokenizer = encoding(model)
  return rough_count(text) unless tokenizer.respond_to?(:encode)

  tokenizer.encode(text).length
rescue StandardError
  rough_count(text)
end