Module: RubyLLM::Agents::Tenant::Incrementable

Extended by:
ActiveSupport::Concern
Included in:
RubyLLM::Agents::Tenant
Defined in:
app/models/ruby_llm/agents/tenant/incrementable.rb

Overview

Provides atomic SQL increment of usage counters after each execution.

Examples:

Recording an execution

tenant.record_execution!(cost: 0.05, tokens: 1200)
tenant.record_execution!(cost: 0.01, tokens: 500, error: true)

Instance Method Summary collapse

Instance Method Details

#record_execution!(cost:, tokens:, error: false) ⇒ void

This method returns an undefined value.

Records an execution by atomically incrementing all counter columns.

Parameters:

  • cost (Numeric)

    The cost of the execution in USD

  • tokens (Integer)

    The number of tokens used

  • error (Boolean) (defaults to: false)

    Whether the execution was an error



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
# File 'app/models/ruby_llm/agents/tenant/incrementable.rb', line 22

def record_execution!(cost:, tokens:, error: false)
  ensure_daily_reset!
  ensure_monthly_reset!

  error_inc = error ? 1 : 0
  status = error ? "error" : "success"

  self.class.where(id: id).update_all(
    self.class.sanitize_sql_array([
      <<~SQL,
        daily_cost_spent = daily_cost_spent + ?,
        monthly_cost_spent = monthly_cost_spent + ?,
        daily_tokens_used = daily_tokens_used + ?,
        monthly_tokens_used = monthly_tokens_used + ?,
        daily_executions_count = daily_executions_count + 1,
        monthly_executions_count = monthly_executions_count + 1,
        daily_error_count = daily_error_count + ?,
        monthly_error_count = monthly_error_count + ?,
        last_execution_at = ?,
        last_execution_status = ?
      SQL
      cost.to_f, cost.to_f,
      tokens.to_i, tokens.to_i,
      error_inc, error_inc,
      Time.current, status
    ])
  )

  reload
  check_soft_cap_alerts!
end