Class: Crimson::CostTracker

Inherits:
Object
  • Object
show all
Defined in:
lib/crimson/cost_tracker.rb

Overview

Per-model cost tracking for API usage.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCostTracker

Returns a new instance of CostTracker.



24
25
26
27
# File 'lib/crimson/cost_tracker.rb', line 24

def initialize
  @total_cost = 0.0
  @cost_breakdown = []
end

Instance Attribute Details

#total_costFloat (readonly)

Returns accumulated cost in USD.

Returns:

  • (Float)

    accumulated cost in USD



22
23
24
# File 'lib/crimson/cost_tracker.rb', line 22

def total_cost
  @total_cost
end

Instance Method Details

#breakdownArray<Hash>

Returns per-turn cost breakdown.

Returns:

  • (Array<Hash>)

    per-turn cost breakdown



51
52
53
# File 'lib/crimson/cost_tracker.rb', line 51

def breakdown
  @cost_breakdown.dup
end

#resetvoid

This method returns an undefined value.

Reset all tracked costs.



57
58
59
60
# File 'lib/crimson/cost_tracker.rb', line 57

def reset
  @total_cost = 0.0
  @cost_breakdown = []
end

#track(model, usage) ⇒ Hash

Record usage for a single turn.

Parameters:

  • model (String)

    model name

  • usage (Hash, nil)

    token usage with prompt_tokens/completion_tokens

Returns:

  • (Hash)

    input/output/total cost for this turn



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/crimson/cost_tracker.rb', line 33

def track(model, usage)
  pricing = MODEL_PRICING[model]
  return { input: 0, output: 0, total: 0 } unless pricing && usage

  prompt_tokens = usage[:prompt_tokens] || usage["prompt_tokens"] || usage[:prompt] || 0
  completion_tokens = usage[:completion_tokens] || usage["completion_tokens"] || usage[:completion] || 0

  input_cost = (pricing[:input] / 1_000_000.0) * prompt_tokens
  output_cost = (pricing[:output] / 1_000_000.0) * completion_tokens
  turn_cost = input_cost + output_cost

  @total_cost += turn_cost
  @cost_breakdown << { input: input_cost, output: output_cost, total: turn_cost }

  { input: input_cost, output: output_cost, total: turn_cost }
end