Module: RubyLLM::Agents::Budget::Forecaster Private

Defined in:
lib/ruby_llm/agents/infrastructure/budget/forecaster.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Budget forecasting based on current spending trends

Class Method Summary collapse

Class Method Details

.calculate_forecast(budget_config:, tenant_id: nil) ⇒ Hash?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Calculates budget forecasts based on current spending trends

Parameters:

  • tenant_id (String, nil) (defaults to: nil)

    The tenant identifier

  • budget_config (Hash)

    Budget configuration

Returns:

  • (Hash, nil)

    Forecast information



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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ruby_llm/agents/infrastructure/budget/forecaster.rb', line 16

def calculate_forecast(budget_config:, tenant_id: nil)
  return nil unless budget_config[:enabled]
  return nil unless budget_config[:global_daily] || budget_config[:global_monthly]

  daily_current = BudgetQuery.current_spend(:global, :daily, tenant_id: tenant_id)
  monthly_current = BudgetQuery.current_spend(:global, :monthly, tenant_id: tenant_id)

  # Calculate hours elapsed today and days elapsed this month
  hours_elapsed = Time.current.hour + (Time.current.min / 60.0)
  hours_elapsed = [hours_elapsed, 1].max # Avoid division by zero
  days_in_month = Time.current.end_of_month.day
  day_of_month = Time.current.day
  days_elapsed = day_of_month - 1 + (hours_elapsed / 24.0)
  days_elapsed = [days_elapsed, 1].max

  forecast = {}

  # Daily forecast
  if budget_config[:global_daily]
    daily_rate = daily_current / hours_elapsed
    projected_daily = daily_rate * 24
    forecast[:daily] = {
      current: daily_current.round(4),
      projected: projected_daily.round(4),
      limit: budget_config[:global_daily],
      on_track: projected_daily <= budget_config[:global_daily],
      hours_remaining: (24 - hours_elapsed).round(1),
      rate_per_hour: daily_rate.round(6)
    }
  end

  # Monthly forecast
  if budget_config[:global_monthly]
    monthly_rate = monthly_current / days_elapsed
    projected_monthly = monthly_rate * days_in_month
    days_remaining = days_in_month - day_of_month
    forecast[:monthly] = {
      current: monthly_current.round(4),
      projected: projected_monthly.round(4),
      limit: budget_config[:global_monthly],
      on_track: projected_monthly <= budget_config[:global_monthly],
      days_remaining: days_remaining,
      rate_per_day: monthly_rate.round(4)
    }
  end

  forecast.presence
end