Class: RubyLLM::Monitoring::MetricsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/ruby_llm/monitoring/metrics_controller.rb

Instance Method Summary collapse

Instance Method Details

#indexObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/controllers/ruby_llm/monitoring/metrics_controller.rb', line 6

def index
  base_scope = Event.group_by_minute(:created_at, range: @time_range, n: @resolution.in_minutes.to_i)

  @metrics = RubyLLM::Monitoring.metrics.map do |klass|
    klass.new(base_scope).as_chart_data
  end

  @totals_by_provider = Event.where(created_at: @time_range)
    .group(:provider, :model)
    .select(
      :provider,
      :model,
      "COUNT(*) as requests",
      "SUM(cost) as cost",
      "AVG(duration) as avg_response_time",
      "SUM(CASE WHEN exception_class IS NOT NULL THEN 1 ELSE 0 END) as error_count"
    ).to_a

  total_requests = @totals_by_provider.sum(&:requests)
  error_count = @totals_by_provider.sum(&:error_count)

  @totals = {
    requests: total_requests,
    cost: @totals_by_provider.sum { |r| r.cost.to_f },
    avg_response_time: @totals_by_provider.any? ? @totals_by_provider.sum do |r|
      r.avg_response_time.to_f * r.requests
    end / total_requests : nil,
    error_rate: total_requests.positive? ? (error_count.to_f / total_requests * 100).round(1) : 0
  }
end