8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
# File 'lib/llms/usage/cost_calculator.rb', line 8
def calculate(usage_data, model = nil)
pricing = model&.pricing || @pricing
components = []
total_cost = 0.0
if usage_data.input_tokens > 0 && pricing[:input]
cost = (usage_data.input_tokens / 1_000_000.0) * pricing[:input]
components << {
type: :input,
tokens: usage_data.input_tokens,
rate: pricing[:input],
cost: cost
}
total_cost += cost
end
if usage_data.output_tokens > 0 && pricing[:output]
cost = (usage_data.output_tokens / 1_000_000.0) * pricing[:output]
components << {
type: :output,
tokens: usage_data.output_tokens,
rate: pricing[:output],
cost: cost
}
total_cost += cost
end
if usage_data.cache_read_tokens > 0 && pricing[:cache_read]
cost = (usage_data.cache_read_tokens / 1_000_000.0) * pricing[:cache_read]
components << {
type: :cache_read,
tokens: usage_data.cache_read_tokens,
rate: pricing[:cache_read],
cost: cost
}
total_cost += cost
end
if usage_data.cache_write_tokens > 0 && pricing[:cache_write]
cost = (usage_data.cache_write_tokens / 1_000_000.0) * pricing[:cache_write]
components << {
type: :cache_write,
tokens: usage_data.cache_write_tokens,
rate: pricing[:cache_write],
cost: cost
}
total_cost += cost
end
{
total_cost: total_cost,
components: components,
currency: 'USD'
}
end
|