Class: LlmCostTracker::LlmApiCall

Inherits:
ActiveRecord::Base
  • Object
show all
Extended by:
PeriodGrouping, TagsColumn
Includes:
TagAccessors
Defined in:
lib/llm_cost_tracker/llm_api_call.rb

Class Method Summary collapse

Methods included from PeriodGrouping

daily_costs, group_by_period

Methods included from TagsColumn

latency_column?, tags_json_column?

Methods included from TagAccessors

#parsed_tags

Class Method Details

.average_latency_msObject



74
75
76
77
78
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 74

def self.average_latency_ms
  return nil unless latency_column?

  average(:latency_ms)&.to_f
end

.by_tag(key, value) ⇒ Object



38
39
40
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 38

def self.by_tag(key, value)
  by_tags(key => value)
end

.by_tags(tags) ⇒ Object



42
43
44
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 42

def self.by_tags(tags)
  TagQuery.apply(self, tags)
end

.cost_by_modelObject



55
56
57
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 55

def self.cost_by_model
  group(:model).sum(:total_cost)
end

.cost_by_providerObject



59
60
61
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 59

def self.cost_by_provider
  group(:provider).sum(:total_cost)
end

.cost_by_tag(key) ⇒ Object



67
68
69
70
71
72
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 67

def self.cost_by_tag(key)
  costs = group_by_tag(key).sum(:total_cost).each_with_object(Hash.new(0.0)) do |(tag_value, cost), grouped|
    grouped[tag_label(tag_value)] += cost.to_f
  end
  costs.sort_by { |_label, cost| -cost }.to_h
end

.group_by_tag(key) ⇒ Object



63
64
65
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 63

def self.group_by_tag(key)
  group(Arel.sql(tag_group_expression(key)))
end

.latency_by_modelObject



80
81
82
83
84
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 80

def self.latency_by_model
  return {} unless latency_column?

  group(:model).average(:latency_ms).transform_values(&:to_f)
end

.latency_by_providerObject



86
87
88
89
90
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 86

def self.latency_by_provider
  return {} unless latency_column?

  group(:provider).average(:latency_ms).transform_values(&:to_f)
end

.total_costObject

Aggregations



47
48
49
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 47

def self.total_cost
  sum(:total_cost).to_f
end

.total_tokensObject



51
52
53
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 51

def self.total_tokens
  sum(:total_tokens).to_i
end