Class: LLMs::Usage::CostCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/llms/usage/cost_calculator.rb

Instance Method Summary collapse

Constructor Details

#initialize(pricing) ⇒ CostCalculator

Returns a new instance of CostCalculator.



4
5
6
# File 'lib/llms/usage/cost_calculator.rb', line 4

def initialize(pricing)
  @pricing = pricing || {}
end

Instance Method Details

#calculate(usage_data, model = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/llms/usage/cost_calculator.rb', line 8

def calculate(usage_data, model = nil)
  pricing = model&.pricing || @pricing
  components = []
  total_cost = 0.0

  if usage_data.input_tokens > 0 && pricing[:input]
    cost = (usage_data.input_tokens / 1_000_000.0) * pricing[:input]
    components << {
      type: :input,
      tokens: usage_data.input_tokens,
      rate: pricing[:input],
      cost: cost
    }
    total_cost += cost
  end

  if usage_data.output_tokens > 0 && pricing[:output]
    cost = (usage_data.output_tokens / 1_000_000.0) * pricing[:output]
    components << {
      type: :output,
      tokens: usage_data.output_tokens,
      rate: pricing[:output],
      cost: cost
    }
    total_cost += cost
  end

  if usage_data.cache_read_tokens > 0 && pricing[:cache_read]
    cost = (usage_data.cache_read_tokens / 1_000_000.0) * pricing[:cache_read]
    components << {
      type: :cache_read,
      tokens: usage_data.cache_read_tokens,
      rate: pricing[:cache_read],
      cost: cost
    }
    total_cost += cost
  end

  if usage_data.cache_write_tokens > 0 && pricing[:cache_write]
    cost = (usage_data.cache_write_tokens / 1_000_000.0) * pricing[:cache_write]
    components << {
      type: :cache_write,
      tokens: usage_data.cache_write_tokens,
      rate: pricing[:cache_write],
      cost: cost
    }
    total_cost += cost
  end

  {
    total_cost: total_cost,
    components: components,
    currency: 'USD'
  }
end

#calculate_simple(input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/llms/usage/cost_calculator.rb', line 64

def calculate_simple(input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0)
  usage_data = UsageData.new(
    input_tokens: input_tokens,
    output_tokens: output_tokens,
    cache_read_tokens: cache_read_tokens,
    cache_write_tokens: cache_write_tokens
  )
  calculate(usage_data)
end