Module: RubyCoded::Chat::State::TokenCost

Included in:
RubyCoded::Chat::State
Defined in:
lib/ruby_coded/chat/state/token_cost.rb

Overview

Provides session cost calculation based on token usage and model pricing. Looks up per-model pricing via RubyLLM’s model registry. Accounts for thinking/reasoning tokens, cached input reads, and cache creation tokens in addition to regular input/output.

Constant Summary collapse

CACHE_CREATION_INPUT_MULTIPLIER =

Anthropic charges 1.25× input price for cache writes. OpenAI reports cache_creation as 0, so this only affects Anthropic.

1.25
UNPRICED_DEFAULTS =
{
  input_price_per_million: nil, output_price_per_million: nil,
  thinking_price_per_million: nil, cached_input_price_per_million: nil,
  cache_creation_price_per_million: nil,
  input_cost: nil, output_cost: nil, thinking_cost: nil,
  cached_cost: nil, cache_creation_cost: nil, total_cost: nil
}.freeze

Instance Method Summary collapse

Instance Method Details

#init_token_costObject



25
26
27
# File 'lib/ruby_coded/chat/state/token_cost.rb', line 25

def init_token_cost
  @model_price_cache = {}
end

#session_cost_breakdownObject

Returns an array of cost breakdown hashes, one per model used. Cost fields are nil when pricing is unavailable.



31
32
33
34
35
36
# File 'lib/ruby_coded/chat/state/token_cost.rb', line 31

def session_cost_breakdown
  token_usage_by_model.map do |model_name, usage|
    pricing = fetch_model_pricing(model_name)
    build_cost_entry(model_name, usage, pricing)
  end
end

#total_session_costObject



38
39
40
41
42
43
44
# File 'lib/ruby_coded/chat/state/token_cost.rb', line 38

def total_session_cost
  breakdown = session_cost_breakdown
  costs = breakdown.map { |entry| entry[:total_cost] }.compact
  return nil if costs.empty?

  costs.sum
end