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?, stream_column?, tags_json_column?, tags_jsonb_column?, tags_mysql_json_column?, usage_source_column?

Methods included from TagAccessors

#parsed_tags

Class Method Details

.average_latency_msObject



82
83
84
85
86
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 82

def self.average_latency_ms
  return nil unless latency_column?

  average(:latency_ms)&.to_f
end

.by_tag(key, value) ⇒ Object



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

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

.by_tags(tags) ⇒ Object



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

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

.cost_by_modelObject



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

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

.cost_by_providerObject



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

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

.cost_by_tag(key) ⇒ Object



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

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



71
72
73
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 71

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

.latency_by_modelObject



88
89
90
91
92
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 88

def self.latency_by_model
  return {} unless latency_column?

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

.latency_by_providerObject



94
95
96
97
98
# File 'lib/llm_cost_tracker/llm_api_call.rb', line 94

def self.latency_by_provider
  return {} unless latency_column?

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

.total_costObject

Aggregations



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

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

.total_tokensObject



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

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