Skip to content

LLM Cost Calculator — Ruby source

Estimate LLM costs per request or per month at billion-token scale — with realistic prompt-cache hit rates, four-lane pricing, and side-by-side model comparison from a dated pricing snapshot.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# llm-cost-calculator — Ruby port: per-million-token cost math for LLM workloads.

# Multiplier applied to Batch API pricing (the standard 50% discount).
BATCH_DISCOUNT = 0.5

# Cost in USD for one workload, or nil when either rate is unpriced:
# ((input_tokens/1e6)*input_per_m + (output_tokens/1e6)*output_per_m)
#   * requests * (batch ? 0.5 : 1).
def cost_for(rates, input)
  return nil if rates[:input_per_m].nil? || rates[:output_per_m].nil?

  base = input[:input_tokens] / 1_000_000.0 * rates[:input_per_m] +
         input[:output_tokens] / 1_000_000.0 * rates[:output_per_m]
  base * input[:requests] * (input[:batch] ? BATCH_DISCOUNT : 1.0)
end

# Output tokens per USD: 1e6 / output_per_m, or nil when unpriced.
def tokens_per_dollar(model)
  rate = model[:output_per_m]
  rate && 1_000_000.0 / rate
end

# Rate cards are never hardcoded in the TS lib — they flow from the model
# snapshot. This demo pins three example cards, one of them unpriced.
models = [
  { id: 'sonnet-class', input_per_m: 3.0, output_per_m: 15.0 },
  { id: 'budget-class', input_per_m: 0.5, output_per_m: 2.0 },
  { id: 'preview', input_per_m: nil, output_per_m: nil } # unpriced model
]
workload = { input_tokens: 12_000, output_tokens: 3_000, requests: 250, batch: true }

rows = models.map do |m|
  { id: m[:id], cost: cost_for(m, workload), tokens_per_dollar: tokens_per_dollar(m) }
end

# Cheapest first, unpriced last, ties by id — the TS comparator as a sort key
# (0/1 flag because Ruby booleans are not comparable inside sort keys).
rows.sort_by! { |r| [r[:cost].nil? ? 1 : 0, r[:cost] || 0.0, r[:id]] }

rows.each do |r|
  line =
    if r[:cost].nil?
      format('%-14s unpriced', r[:id])
    else
      format('%-14s $%.4f  (%.0f output tokens/USD)', r[:id], r[:cost], r[:tokens_per_dollar])
    end
  puts line
end

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →