Class: AgentC::Costs::Report::Calculator

Inherits:
Object
  • Object
show all
Defined in:
lib/agent_c/costs/report.rb

Overview

Calculator class for computing costs

Instance Method Summary collapse

Instance Method Details

#calculate(messages) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/agent_c/costs/report.rb', line 117

def calculate(messages)
  stats = {
    input_tokens: 0,
    output_tokens: 0,
    cached_tokens: 0,
    cache_creation_tokens: 0,
    input_cost: 0.0,
    output_cost: 0.0,
    cached_cost: 0.0,
    cache_creation_cost: 0.0,
    total_cost: 0.0,
    message_count: messages.count
  }

  messages.each do |message|
    stats[:input_tokens] += message.input_tokens || 0
    stats[:output_tokens] += message.output_tokens || 0
    stats[:cached_tokens] += message.cached_tokens || 0
    stats[:cache_creation_tokens] += message.cache_creation_tokens || 0

    # Determine which pricing tier to use based on total token count
    total_message_tokens = (message.input_tokens || 0) +
                           (message.cached_tokens || 0) +
                           (message.cache_creation_tokens || 0)
    pricing = total_message_tokens > LONG_CONTEXT_THRESHOLD ? PRICING[:long] : PRICING[:normal]

    # Calculate cost using appropriate pricing tier
    # Input tokens cost
    if message.input_tokens && message.input_tokens > 0
      cost = (message.input_tokens / 1_000_000.0) * pricing[:input]
      stats[:input_cost] += cost
      stats[:total_cost] += cost
    end

    # Output tokens cost
    if message.output_tokens && message.output_tokens > 0
      cost = (message.output_tokens / 1_000_000.0) * pricing[:output]
      stats[:output_cost] += cost
      stats[:total_cost] += cost
    end

    # Cached tokens cost (cache read)
    if message.cached_tokens && message.cached_tokens > 0
      cost = (message.cached_tokens / 1_000_000.0) * pricing[:cached_input]
      stats[:cached_cost] += cost
      stats[:total_cost] += cost
    end

    # Cache creation tokens cost
    if message.cache_creation_tokens && message.cache_creation_tokens > 0
      cost = (message.cache_creation_tokens / 1_000_000.0) * pricing[:cache_creation]
      stats[:cache_creation_cost] += cost
      stats[:total_cost] += cost
    end
  end

  stats
end