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
|
# File 'lib/llm_cost_tracker/tracker.rb', line 16
def record(event:, latency_ms: nil, metadata: {}, context_tags: nil, enforce_budget: false)
return unless LlmCostTracker.configuration.enabled
calculation = Pricing::Calculation.for(
provider: event.provider,
model: event.model,
tokens: event.token_usage,
line_items: event.line_items,
pricing_mode: event.pricing_mode,
usage_source: event.usage_source
)
tags = build_tags(context_tags: context_tags, metadata: metadata)
if calculation.token_cost.nil? && event.token_usage.total_tokens.positive? &&
calculation.priced_line_items.none?(&:priced?)
Pricing::Unknown.process(event.model, pricing_mode: calculation.mode)
end
event = build_event(event: event, calculation: calculation, tags: tags, latency_ms: latency_ms)
if Ingestion.async?
Ingestion::Inbox.save(event)
Ingestion::Worker.ensure_started
else
Ledger::Store.insert(event)
end
yield if block_given?
notify_subscribers(event)
behavior_override = :raise if enforce_budget
Budget.check!(event, behavior_override: behavior_override)
Budget.check_persisted!([event], behavior_override: behavior_override) unless Ingestion.async?
event
end
|