Class: LlmCostTracker::LlmApiCall

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

Class Method Summary collapse

Methods included from TagsColumn

latency_column?, tags_json_column?

Methods included from TagAccessors

#parsed_tags

Class Method Details

.average_latency_msObject



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

def self.average_latency_ms
  return nil unless latency_column?

  average(:latency_ms)&.to_f
end

.by_tag(key, value) ⇒ Object



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

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

.by_tags(tags) ⇒ Object



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

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

.cost_by_modelObject



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

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

.cost_by_providerObject



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

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

.cost_by_tag(key) ⇒ Object



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

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

.daily_costs(days: 30) ⇒ Object



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

def self.daily_costs(days: 30)
  where(tracked_at: days.days.ago..)
    .group("DATE(tracked_at)")
    .sum(:total_cost)
    .transform_keys(&:to_s)
end

.group_by_tag(key) ⇒ Object



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

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

.latency_by_modelObject



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

def self.latency_by_model
  return {} unless latency_column?

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

.latency_by_providerObject



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

def self.latency_by_provider
  return {} unless latency_column?

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

.total_costObject

Aggregations



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

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

.total_tokensObject



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

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