Class: LittleGhost::Usage

Inherits:
Object
  • Object
show all
Defined in:
lib/little_ghost/usage.rb

Overview

Usage makes token accounting consistent across model providers. It keeps input, output, cache, and reasoning counts separate so applications can aggregate them without double-counting.

Providers report uncached input, visible output, cache reads, cache writes, and reasoning separately. Invalid or negative values normalize to zero.

Constant Summary collapse

FIELDS =

:nodoc:

%i[input_tokens output_tokens cache_read_tokens cache_write_tokens reasoning_tokens].freeze

Instance Method Summary collapse

Constructor Details

#initialize(input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: 0) ⇒ Usage

Normalizes provider token counts; invalid or negative values become zero.



16
17
18
19
20
21
22
# File 'lib/little_ghost/usage.rb', line 16

def initialize(input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: 0)
  @input_tokens = integer(input_tokens)
  @output_tokens = integer(output_tokens)
  @cache_read_tokens = integer(cache_read_tokens)
  @cache_write_tokens = integer(cache_write_tokens)
  @reasoning_tokens = integer(reasoning_tokens)
end

Instance Method Details

#+(other) ⇒ Object

Adds two usage values field by field.



30
31
32
# File 'lib/little_ghost/usage.rb', line 30

def +(other)
  self.class.new(**FIELDS.to_h { |field| [field, public_send(field) + other.public_send(field)] })
end

#to_hObject

Exposes every field and total_tokens as a hash.



35
36
37
# File 'lib/little_ghost/usage.rb', line 35

def to_h
  FIELDS.to_h { |field| [field, public_send(field)] }.merge(total_tokens: total_tokens)
end

#total_tokensObject

Sums every normalized token field.



25
26
27
# File 'lib/little_ghost/usage.rb', line 25

def total_tokens
  FIELDS.sum { |field| public_send(field) }
end