Skip to content

AI Text Summarizer — Kotlin source

Paste any text and get an LLM summary — TL;DR, bullets, or detailed — using your own free Groq key, called straight from your browser.

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

// text-summarizer — prompt building, reply cleanup, and text stats.
//
// Language: Kotlin (JVM, standard library only)
// CosmoDev polyglot showcase port of the `text-summarizer` tool, ported
// from src/lib/summarize.ts (the canonical TypeScript implementation).
//
// Kotlin's Regex and stdlib carry the TS lib almost verbatim, and the JVM
// string is UTF-16, so String.length IS the JS .length — chars and the
// truncation cut need no unit juggling. Top-level functions keep the file
// as flat as the TS module it mirrors.
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Run: kotlinc kotlin.kt -include-runtime -d summarizer.jar && java -jar summarizer.jar

/** Styles, mirroring the TS SummaryStyle union. */
val STYLES = listOf("tldr", "bullets", "detailed")

/** Input cap: longer pastes are cut (and marked) before reaching the model. */
const val MAX_INPUT_CHARS = 12000

/** The per-style system-prompt contract, byte-for-byte the TS lib's. */
val STYLE_CONTRACT = mapOf(
    "tldr" to
        "Summarize the text as ONE sentence of at most 25 words. Plain text, no preamble, no bullets.",
    "bullets" to
        "Summarize the text as 3 to 6 markdown bullets, each starting with \"- \" and covering one " +
            "distinct point. No preamble, no closing remark.",
    "detailed" to
        "Summarize the text as 2 to 4 short paragraphs: what it is about, the key facts, and the " +
            "outcome or next step. No preamble, no headings.",
)

/** Word / sentence / character counts, tolerant of empty input. */
data class Stats(val words: Int, val sentences: Int, val chars: Int)

/** One [role, content] chat message for the provider layer. */
data class Message(val role: String, val content: String)

private val TERMINATOR_RUNS = Regex("[.!?]+")
private val CODE_FENCES = Regex("```[a-z]*\n?")

/**
 * Count words / sentences / characters; tolerant of empty input. Chars is
 * String.length — UTF-16 code units, like JS .length, so astral characters
 * (emoji, etc.) count 2 with no extra code. Sentences count TERMINATOR
 * runs, never the quadratic body regex, the trap the TS lib's comment
 * documents.
 */
fun textStats(text: String): Stats {
    val trimmed = text.trim()
    val words = if (trimmed.isEmpty()) 0 else trimmed.split(Regex("\\s+")).size
    return Stats(words, TERMINATOR_RUNS.findAll(text).count(), text.length)
}

/**
 * Build the [system, user] chat messages for the provider layer; long
 * pastes are cut at MAX_INPUT_CHARS UTF-16 units — exactly the JS
 * slice(0, limit) — and marked with a visible truncation note.
 *
 * @throws IllegalArgumentException on a style outside STYLES (the TS union
 *     makes that state unrepresentable; Kotlin throws instead).
 */
fun buildPromptMessages(text: String, style: String = "tldr"): List<Message> {
    val contract = STYLE_CONTRACT[style]
        ?: throw IllegalArgumentException("unknown style: $style")
    val stats = textStats(text)
    val body = if (text.length > MAX_INPUT_CHARS) {
        text.substring(0, MAX_INPUT_CHARS) + "\n… (text truncated)"
    } else {
        text
    }
    return listOf(
        Message("system", "You summarize text faithfully. $contract"),
        Message(
            "user",
            "Summarize the following text ($style style; ${stats.words} words, " +
                "${stats.sentences} sentences).\n\n$body",
        ),
    )
}

/**
 * Clean the model's reply into displayable summary text — any non-empty
 * cleaned text is the summary; null only when nothing survives.
 */
fun parseSummary(text: String): String? = CODE_FENCES.replace(text, "").trim().ifEmpty { null }

fun main() {
    val s = textStats("Hello world. Hi! Am I tidy?  ")
    println("words=${s.words} sentences=${s.sentences} chars=${s.chars}")

    for (m in buildPromptMessages("paste here")) println("${m.role}: ${m.content}")

    println(parseSummary("```text\nthe summary\n```")) // the summary
    println(parseSummary("   \n"))                     // null

    try {
        buildPromptMessages("x", "haiku")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}

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 →