Class: ClaudeUsage::CostCalculator

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

Constant Summary collapse

TIERED_THRESHOLD =
200_000

Instance Method Summary collapse

Constructor Details

#initializeCostCalculator

Returns a new instance of CostCalculator.



7
8
9
# File 'lib/claude_usage/cost_calculator.rb', line 7

def initialize
  @pricing_fetcher = LiteLLMPricingFetcher.new
end

Instance Method Details

#calculate_cost(entry) ⇒ Object



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
# File 'lib/claude_usage/cost_calculator.rb', line 11

def calculate_cost(entry)
  return entry[:pre_calculated_cost] if entry[:pre_calculated_cost]

  # Skip if no model information
  return 0 if entry[:model].nil? || entry[:model].empty?

  model_pricing = @pricing_fetcher.get_model_pricing(entry[:model])
  return 0 unless model_pricing

  calculate_tiered_cost(
    entry[:input_tokens],
    model_pricing[:input_cost_per_token],
    model_pricing[:input_cost_per_token_above_200k]
  ) +
    calculate_tiered_cost(
      entry[:output_tokens],
      model_pricing[:output_cost_per_token],
      model_pricing[:output_cost_per_token_above_200k]
    ) +
    calculate_tiered_cost(
      entry[:cache_creation_tokens],
      model_pricing[:cache_creation_input_token_cost],
      model_pricing[:cache_creation_cost_above_200k]
    ) +
    calculate_tiered_cost(
      entry[:cache_read_tokens],
      model_pricing[:cache_read_input_token_cost],
      model_pricing[:cache_read_cost_above_200k]
    )
end