Class: Ask::Monitoring::EventSubscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/ask/monitoring/event_subscriber.rb

Overview

Subscribes to Ask::Instrumentation events and persists them to the database via the Ask::Event model.

Each event is stored with:

  • name, provider, model, duration, token counts

  • calculated cost via Cost.for

  • error information (when present)

  • metadata context from Ask::Instrumentation.current_metadata

Instance Method Summary collapse

Instance Method Details

#call(event) ⇒ Object

Called by ActiveSupport::Notifications for each matching event.

Parameters:

  • event (ActiveSupport::Notifications::Event)

    The instrumentation event



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ask/monitoring/event_subscriber.rb', line 15

def call(event)
  payload = event.payload

  Ask::Event.create!(
    name:           event.name,
    provider:       payload[:provider],
    model:          payload[:model],
    duration:       event.duration,
    input_tokens:   payload[:input_tokens],
    output_tokens:  payload[:output_tokens],
    cost:           calculate_cost(payload),
    error:          payload[:error],
    metadata:       Ask::Instrumentation.
  )
rescue => e
  # Never let a persistence failure break the calling code.
  Rails.logger.warn("[ask-monitoring] Failed to persist event: #{e.message}")
end