Module: LlmCostTracker::Pricing::Estimator

Defined in:
lib/llm_cost_tracker/pricing/estimator.rb

Constant Summary collapse

CHARS_PER_TOKEN =
4

Class Method Summary collapse

Class Method Details

.call(provider:, model:, request:) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/llm_cost_tracker/pricing/estimator.rb', line 10

def self.call(provider:, model:, request:)
  chars = char_count(request)
  return BigDecimal("0") if chars.zero?

  estimated_tokens = (chars.to_f / CHARS_PER_TOKEN).ceil
  cost_data = Pricing.cost_for(
    provider: provider,
    model: model,
    tokens: { input: estimated_tokens }
  )
  cost_data && BigDecimal(cost_data[:total_cost].to_s)
end

.char_count(value) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/llm_cost_tracker/pricing/estimator.rb', line 23

def self.char_count(value)
  case value
  when String then value.length
  when Hash then value.values.sum { |nested| char_count(nested) }
  when Array then value.sum { |nested| char_count(nested) }
  else 0
  end
end