Class: Crimson::CostTracker
- Inherits:
-
Object
- Object
- Crimson::CostTracker
- Defined in:
- lib/crimson/cost_tracker.rb
Overview
Per-model cost tracking for API usage.
Instance Attribute Summary collapse
-
#total_cost ⇒ Float
readonly
Accumulated cost in USD.
Instance Method Summary collapse
-
#breakdown ⇒ Array<Hash>
Per-turn cost breakdown.
-
#initialize ⇒ CostTracker
constructor
A new instance of CostTracker.
-
#reset ⇒ void
Reset all tracked costs.
-
#track(model, usage) ⇒ Hash
Record usage for a single turn.
Constructor Details
#initialize ⇒ CostTracker
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_cost ⇒ Float (readonly)
Returns accumulated cost in USD.
22 23 24 |
# File 'lib/crimson/cost_tracker.rb', line 22 def total_cost @total_cost end |
Instance Method Details
#breakdown ⇒ Array<Hash>
Returns per-turn cost breakdown.
51 52 53 |
# File 'lib/crimson/cost_tracker.rb', line 51 def breakdown @cost_breakdown.dup end |
#reset ⇒ void
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.
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 |