LLM Cost Calculator — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// llm-cost-calculator — Kotlin port: per-million-token cost math for LLM workloads.
/** Multiplier applied to Batch API pricing (the standard 50% discount). */
const val BATCH_DISCOUNT = 0.5
/** Price pair for a model or a custom rate card. null = unpriced. */
data class CostRates(val inputPerM: Double?, val outputPerM: Double?)
/** One workload to price. */
data class CostInput(
val inputTokens: Long,
val outputTokens: Long,
val requests: Long = 1,
val batch: Boolean = false,
)
/** Pricing projection of a model — the only three fields cost math needs. */
data class Model(val id: String, val inputPerM: Double?, val outputPerM: Double?)
/** Cost in USD, or null when either rate is unpriced:
* ((in/1e6)·input + (out/1e6)·output) × requests × batch discount. */
fun costFor(rates: CostRates, work: CostInput): Double? {
val input = rates.inputPerM ?: return null
val output = rates.outputPerM ?: return null
val base = work.inputTokens / 1e6 * input + work.outputTokens / 1e6 * output
return base * work.requests * if (work.batch) BATCH_DISCOUNT else 1.0
}
/** Output tokens per USD: 1e6 / outputPerM, or null when unpriced. */
fun tokensPerDollar(m: Model): Double? = m.outputPerM?.let { 1e6 / it }
fun main() {
val models = listOf(
Model("sonnet-class", 3.0, 15.0),
Model("budget-class", 0.5, 2.0),
Model("preview", null, null), // unpriced model
)
val work = CostInput(inputTokens = 12_000, outputTokens = 3_000, requests = 250, batch = true)
// Cheapest first, unpriced last, ties by id — the TS comparator as a sort key.
models.sortedWith(
compareBy(
{ costFor(CostRates(it.inputPerM, it.outputPerM), work) == null },
{ costFor(CostRates(it.inputPerM, it.outputPerM), work) ?: 0.0 },
{ it.id },
)
).forEach { m ->
val cost = costFor(CostRates(m.inputPerM, m.outputPerM), work)
println(
if (cost != null) "%-14s $%.4f (%,.0f output tokens/USD)".format(m.id, cost, tokensPerDollar(m) ?: 0.0)
else "%-14s unpriced".format(m.id)
)
}
}
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 →