LLM Cost Calculator — Swift 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 Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// llm-cost-calculator — Swift port: per-million-token cost math for LLM workloads.
import Foundation
/// Multiplier applied to Batch API pricing (the standard 50% discount).
let batchDiscount = 0.5
/// Price pair for a model or a custom rate card. nil = unpriced.
struct CostRates {
var inputPerM: Double? // USD per 1M input tokens.
var outputPerM: Double? // USD per 1M output tokens.
}
/// One workload to price.
struct CostInput {
var inputTokens: Double // Input tokens per request.
var outputTokens: Double // Output tokens per request.
var requests: Double = 1
var batch = false
}
/// Pricing projection of a model — the only three fields cost math needs.
struct Model {
var id: String
var inputPerM: Double?
var outputPerM: Double?
}
/// Cost in USD, or nil when either rate is unpriced:
/// ((in/1e6)·input + (out/1e6)·output) × requests × batch discount.
func costFor(_ rates: CostRates, _ work: CostInput) -> Double? {
guard let inputPerM = rates.inputPerM, let outputPerM = rates.outputPerM else { return nil }
let base = work.inputTokens / 1_000_000 * inputPerM
+ work.outputTokens / 1_000_000 * outputPerM
return base * work.requests * (work.batch ? batchDiscount : 1)
}
/// Output tokens per USD: 1e6 / outputPerM, or nil when unpriced.
func tokensPerDollar(_ model: Model) -> Double? {
model.outputPerM.map { 1_000_000 / $0 }
}
let models = [
Model(id: "sonnet-class", inputPerM: 3.0, outputPerM: 15.0),
Model(id: "budget-class", inputPerM: 0.5, outputPerM: 2.0),
Model(id: "preview", inputPerM: nil, outputPerM: nil), // unpriced model
]
let work = CostInput(inputTokens: 12_000, outputTokens: 3_000, requests: 250, batch: true)
// Cheapest first, unpriced last, ties by id — the TS comparator verbatim.
let rows = models
.map { m in
(id: m.id,
cost: costFor(CostRates(inputPerM: m.inputPerM, outputPerM: m.outputPerM), work),
tpd: tokensPerDollar(m))
}
.sorted { a, b in
switch (a.cost, b.cost) {
case let (priced?, otherPriced?):
return priced == otherPriced ? a.id < b.id : priced < otherPriced
case (nil, nil):
return a.id < b.id
case (nil, _):
return false // nil sorts last
default:
return true
}
}
for row in rows {
let label = row.id.padding(toLength: 14, withPad: " ", startingAt: 0)
if let cost = row.cost {
print("\(label)$\(String(format: "%.4f", cost)) (\(Int(row.tpd ?? 0)) output tokens/USD)")
} else {
print("\(label)unpriced")
}
}
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 →