Module: Legion::LLM::Metering
- Extended by:
- Legion::Logging::Helper
- Defined in:
- lib/legion/llm/metering.rb,
lib/legion/llm/metering/tokens.rb,
lib/legion/llm/metering/tracker.rb,
lib/legion/llm/metering/estimator.rb
Defined Under Namespace
Modules: Pricing, Recorder, Tokens
Constant Summary
collapse
- SPOOL_DIR =
File.expand_path('~/.legionio/data/spool/metering')
- SPOOL_FILE =
File.join(SPOOL_DIR, 'events.jsonl').freeze
- SPOOL_MUTEX =
Mutex.new
Class Method Summary
collapse
Class Method Details
.attributed_event(event) ⇒ Object
.const_missing(name) ⇒ Object
Backward-compat: resolve old Legion::LLM::Metering::Exchange, ::Event
248
249
250
251
252
253
254
255
256
257
258
259
|
# File 'lib/legion/llm/metering.rb', line 248
def self.const_missing(name)
case name
when :Exchange
require_relative 'transport/exchanges/metering'
Transport::Exchanges::Metering
when :Event
require_relative 'transport/messages/metering_event'
Transport::Messages::MeteringEvent
else
super
end
end
|
.emit(event) ⇒ Object
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# File 'lib/legion/llm/metering.rb', line 29
def emit(event)
event = attributed_event(event)
event_class = metering_event_class if transport_connected?
if event_class
event_class.new(**event).publish
log.info("[llm][metering] published provider=#{event[:provider]} model=#{event[:model_id]}")
:published
else
spool_event(event)
log.info("[llm][metering] spooled provider=#{event[:provider]} model=#{event[:model_id]} reason=transport_unavailable")
:spooled
end
rescue StandardError => e
handle_exception(e, level: :warn, operation: 'llm.metering.emit')
:dropped
end
|
.enforce_max_events ⇒ Object
212
213
214
215
216
217
218
219
220
221
222
223
224
|
# File 'lib/legion/llm/metering.rb', line 212
def enforce_max_events
path = spool_file_path
return unless File.exist?(path)
max = spool_settings[:max_events] || 10_000
lines = File.readlines(path, chomp: true)
return if lines.size < max
trimmed = lines.last(max - 1)
File.write(path, trimmed.map { |l| "#{l}\n" }.join)
log.debug("[llm][metering] enforce_max_events trimmed=#{lines.size - trimmed.size} max=#{max}")
end
|
.ensure_spool_dir ⇒ Object
226
227
228
|
# File 'lib/legion/llm/metering.rb', line 226
def ensure_spool_dir
FileUtils.mkdir_p(spool_dir_path)
end
|
163
164
165
166
167
168
169
170
|
# File 'lib/legion/llm/metering.rb', line 163
def (hash, key)
return nil unless hash.respond_to?(:key?)
string_key = key.to_s
return hash[string_key] if hash.key?(string_key)
hash[key] if hash.key?(key)
end
|
157
158
159
160
161
|
# File 'lib/legion/llm/metering.rb', line 157
def (response)
return nil unless response.is_a?(Hash)
((response, :meta), :model) || (response, :model)
end
|
151
152
153
154
155
|
# File 'lib/legion/llm/metering.rb', line 151
def (response)
return nil unless response.is_a?(Hash)
((response, :meta), :provider) || (response, :provider)
end
|
141
142
143
144
145
146
147
148
149
|
# File 'lib/legion/llm/metering.rb', line 141
def (response)
return { input_tokens: 0, output_tokens: 0 } unless response.is_a?(Hash)
usage = (response, :usage) || {}
{
input_tokens: (usage, :input_tokens) || (usage, :prompt_tokens) || 0,
output_tokens: (usage, :output_tokens) || (usage, :completion_tokens) || 0
}
end
|
.flush_spool ⇒ Object
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
# File 'lib/legion/llm/metering.rb', line 54
def flush_spool
return 0 unless File.exist?(spool_file_path)
event_class = metering_event_class
unless event_class && transport_connected?
log.debug('[llm][metering] flush_spool skipped reason=transport_unavailable')
return 0
end
events = SPOOL_MUTEX.synchronize do
path = spool_file_path
return 0 unless File.exist?(path)
lines = File.readlines(path, chomp: true)
parsed = lines.filter_map do |line|
next if line.strip.empty?
Legion::JSON.load(line)
end
File.write(path, '')
parsed
end
return 0 if events.empty?
batch_sleep = spool_settings[:flush_batch_sleep] || 0.0
flushed = 0
events.each_with_index do |event_data, index|
event_class.new(**event_data).publish
flushed += 1
sleep(batch_sleep) if batch_sleep.positive? && index < events.size - 1
end
log.info("[llm][metering] flush_spool flushed=#{flushed}")
flushed
rescue StandardError => e
handle_exception(e, level: :warn, operation: 'llm.metering.flush_spool')
0
end
|
.install_hook ⇒ Object
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
# File 'lib/legion/llm/metering.rb', line 97
def install_hook
Legion::LLM::Hooks.after_chat do |response:, model:, caller: nil, **|
usage = (response)
next if usage[:input_tokens].zero? && usage[:output_tokens].zero?
resolved_model = ((response) || model).to_s
resolved_provider = (response)
Metering::Recorder.record(
model: resolved_model,
input_tokens: usage[:input_tokens],
output_tokens: usage[:output_tokens],
provider: resolved_provider
)
emit(
provider: resolved_provider,
model_id: resolved_model,
input_tokens: usage[:input_tokens],
output_tokens: usage[:output_tokens],
caller: caller,
event_type: 'llm_completion',
status: response.is_a?(Hash) && response[:error] ? 'failure' : 'success'
)
nil
end
end
|
.load_transport ⇒ Object
20
21
22
23
24
25
|
# File 'lib/legion/llm/metering.rb', line 20
def self.load_transport
return unless defined?(Legion::Transport::Message)
require_relative 'transport/exchanges/metering'
require_relative 'transport/messages/metering_event'
end
|
.metering_event_class ⇒ Object
.read_spool ⇒ Object
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
|
# File 'lib/legion/llm/metering.rb', line 186
def read_spool
SPOOL_MUTEX.synchronize do
path = spool_file_path
return [] unless File.exist?(path)
lines = File.readlines(path, chomp: true)
lines.filter_map do |line|
next if line.strip.empty?
Legion::JSON.load(line)
end
end
rescue StandardError => e
handle_exception(e, level: :warn, operation: 'llm.metering.read_spool')
[]
end
|
.spool_dir_path ⇒ Object
243
244
245
|
# File 'lib/legion/llm/metering.rb', line 243
def spool_dir_path
File.dirname(spool_file_path)
end
|
.spool_event(event) ⇒ Object
— Spool internals (private) —
174
175
176
177
178
179
180
181
182
183
184
|
# File 'lib/legion/llm/metering.rb', line 174
def spool_event(event)
SPOOL_MUTEX.synchronize do
ensure_spool_dir
enforce_max_events
line = Legion::JSON.dump(event)
File.open(spool_file_path, 'a') { |f| f.puts(line) }
end
log.debug("[llm][metering] spool_event written provider=#{event[:provider]} model=#{event[:model_id]}")
rescue StandardError => e
handle_exception(e, level: :warn, operation: 'llm.metering.spool_event')
end
|
.spool_file_path ⇒ Object
Resolve spool file path at call time, honouring operator-configured paths (e.g. for containerised deployments where $HOME is not writable). Falls back to the compile-time SPOOL_FILE constant.
238
239
240
241
|
# File 'lib/legion/llm/metering.rb', line 238
def spool_file_path
configured = spool_settings[:path]
configured && !configured.to_s.strip.empty? ? configured.to_s : SPOOL_FILE
end
|
.spool_settings ⇒ Object
230
231
232
233
|
# File 'lib/legion/llm/metering.rb', line 230
def spool_settings
settings = Legion::LLM::Settings.value(:metering, :spool, default: {})
settings.is_a?(Hash) ? settings : {}
end
|
.transport_connected? ⇒ Boolean
.truncate_spool ⇒ Object
203
204
205
206
207
208
209
210
|
# File 'lib/legion/llm/metering.rb', line 203
def truncate_spool
SPOOL_MUTEX.synchronize do
path = spool_file_path
File.write(path, '') if File.exist?(path)
end
rescue StandardError => e
handle_exception(e, level: :warn, operation: 'llm.metering.truncate_spool')
end
|