Class: LlmCostTracker::Tracker

Inherits:
Object
  • Object
show all
Defined in:
lib/llm_cost_tracker/tracker.rb

Constant Summary collapse

EVENT_NAME =
"llm_request.llm_cost_tracker"

Class Method Summary collapse

Class Method Details

.enforce_budget!Object



17
18
19
20
21
# File 'lib/llm_cost_tracker/tracker.rb', line 17

def enforce_budget!
  return unless LlmCostTracker.configuration.enabled

  Budget.enforce!
end

.record(capture:, latency_ms: nil, pricing_mode: nil, metadata: {}, context_tags: nil) ⇒ Object



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 'lib/llm_cost_tracker/tracker.rb', line 23

def record(capture:, latency_ms: nil, pricing_mode: nil, metadata: {}, context_tags: nil)
  return unless LlmCostTracker.configuration.enabled

  pricing_mode = Pricing.normalize_mode(pricing_mode) || capture.pricing_mode
  cost_data, pricing_snapshot = Pricing.cost_and_snapshot_for(
    provider: capture.provider,
    model: capture.model,
    tokens: capture.token_usage,
    pricing_mode: pricing_mode
  )

  Pricing::Unknown.handle!(capture.model) if cost_data.nil? && capture.token_usage.total_tokens.positive?

  event = build_event(
    capture: capture,
    pricing_mode: pricing_mode,
    cost_data: cost_data,
    pricing_snapshot: pricing_snapshot,
    metadata: ,
    latency_ms: latency_ms,
    context_tags: context_tags
  )

  ActiveSupport::Notifications.instrument(EVENT_NAME, event.to_h)

  Ingestion::Inbox.save(event)
  Budget.check!(event)

  event
end