Class: LlmCostTracker::Storage::ActiveRecordStore

Inherits:
Object
  • Object
show all
Defined in:
lib/llm_cost_tracker/storage/active_record_store.rb

Class Method Summary collapse

Class Method Details

.daily_total(time: Time.now.utc) ⇒ Object



49
50
51
# File 'lib/llm_cost_tracker/storage/active_record_store.rb', line 49

def daily_total(time: Time.now.utc)
  ActiveRecordRollups.daily_total(time: time)
end

.monthly_total(time: Time.now.utc) ⇒ Object



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

def monthly_total(time: Time.now.utc)
  ActiveRecordRollups.monthly_total(time: time)
end

.reset!Object



9
10
11
# File 'lib/llm_cost_tracker/storage/active_record_store.rb', line 9

def reset!
  ActiveRecordRollups.reset!
end

.save(event) ⇒ Object



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
# File 'lib/llm_cost_tracker/storage/active_record_store.rb', line 13

def save(event)
  tags = stringify_tags(event.tags || {})
  model = LlmCostTracker::LlmApiCall
  columns = model.columns_hash

  attributes = {
    provider:      event.provider,
    model:         event.model,
    input_tokens:  event.input_tokens,
    output_tokens: event.output_tokens,
    total_tokens:  event.total_tokens,
    input_cost:    event.cost&.input_cost,
    output_cost:   event.cost&.output_cost,
    total_cost:    event.cost&.total_cost,
    tags:          tags_for_storage(tags, model),
    tracked_at:    event.tracked_at
  }
  optional_attributes(event).each do |name, value|
    attributes[name] = value if columns.key?(name.to_s)
  end
  attributes[:latency_ms] = event.latency_ms if columns.key?("latency_ms")
  attributes[:stream] = event.stream if columns.key?("stream")
  attributes[:usage_source] = event.usage_source if columns.key?("usage_source")
  attributes[:provider_response_id] = event.provider_response_id if columns.key?("provider_response_id")

  model.transaction do
    call = model.create!(attributes)
    ActiveRecordRollups.increment!(event)
    call
  end
end