Module: Legion::Extensions::Metering::Helpers::Economics

Defined in:
lib/legion/extensions/metering/helpers/economics.rb

Constant Summary collapse

PERIOD_DAYS =
{ daily: 1, weekly: 7, monthly: 30 }.freeze

Instance Method Summary collapse

Instance Method Details

#budget_forecast(days: 30) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/legion/extensions/metering/helpers/economics.rb', line 57

def budget_forecast(days: 30, **)
  return { projected_cost: 0, trend: :flat } unless defined?(Legion::Data)

  recent_ds = Legion::Data.connection[:metering_records]
                          .where(Sequel.lit('recorded_at >= ?', Time.now - 86_400))
  daily_cost = (recent_ds.sum(:input_tokens).to_i + recent_ds.sum(:output_tokens).to_i) *
               cost_per_token

  { projected_cost: daily_cost * days, daily_average: daily_cost, days: days,
    trend: daily_cost.positive? ? :active : :flat }
end

#payroll_summary(period: :daily) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/legion/extensions/metering/helpers/economics.rb', line 10

def payroll_summary(period: :daily, **)
  return { workers: [], total_cost: 0, avg_productivity: 0 } unless defined?(Legion::Data)

  days = PERIOD_DAYS.fetch(period.to_sym, 1)
  cutoff = Time.now - (days * 86_400)
  ds = Legion::Data.connection[:metering_records].where(Sequel.lit('recorded_at >= ?', cutoff))

  workers = ds.group_and_count(:worker_id).all.map do |row|
    {
      worker_id:  row[:worker_id],
      task_count: row[:count],
      cost:       ds.where(worker_id: row[:worker_id]).sum(:input_tokens).to_f * cost_per_token,
      autonomy:   synapse_autonomy(row[:worker_id])
    }
  end

  total = workers.sum { |w| w[:cost] }
  avg_prod = workers.empty? ? 0 : workers.sum { |w| w[:task_count] } / workers.size.to_f

  { workers: workers, total_cost: total, avg_productivity: avg_prod, period: period }
end

#worker_report(worker_id:, period: :daily) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/legion/extensions/metering/helpers/economics.rb', line 32

def worker_report(worker_id:, period: :daily, **)
  return { salary: 0, overtime: 0, productivity: 0 } unless defined?(Legion::Data)

  days = PERIOD_DAYS.fetch(period.to_sym, 1)
  cutoff = Time.now - (days * 86_400)
  ds = Legion::Data.connection[:metering_records]
                   .where(worker_id: worker_id)
                   .where(Sequel.lit('recorded_at >= ?', cutoff))

  task_count = ds.count
  total_tokens = ds.sum(:input_tokens).to_i + ds.sum(:output_tokens).to_i
  salary = total_tokens.to_f * cost_per_token
  avg_latency = ds.avg(:latency_ms).to_f

  {
    worker_id:      worker_id,
    salary:         salary,
    overtime:       0,
    productivity:   task_count,
    avg_latency:    avg_latency,
    autonomy_level: synapse_autonomy(worker_id),
    period:         period
  }
end