Skip to content

AI Text Summarizer — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package textsummarizer is the Go twin of CosmoDev's src/lib/summarize.ts —
// the pure core of the AI text summarizer. Pure + deterministic, no panics.
//
// Language: Go (standard library only).
// CosmoDev polyglot showcase port of the `text-summarizer` tool, ported from
// src/lib/summarize.ts (the canonical TypeScript implementation).
//
// Sentences count TERMINATOR runs (the body regex is quadratic); chars
// counts UTF-16 code units, like JS .length.
//
// display source — part of CosmoDev's polyglot tool pages.
package textsummarizer

import (
	"fmt"
	"regexp"
	"strings"
	"unicode/utf16"
)

// Style selects the summary contract, mirroring the TS SummaryStyle union.
type Style string

const (
	StyleTldr     Style = "tldr"
	StyleBullets  Style = "bullets"
	StyleDetailed Style = "detailed"
)

// MaxInputChars caps pastes; longer input is cut (and marked) upstream.
const MaxInputChars = 12000

// Stats holds word / sentence / character counts, tolerant of empty input.
type Stats struct {
	Words     int
	Sentences int
	Chars     int
}

// Message is one [role, content] chat message for the provider layer.
type Message struct {
	Role    string
	Content string
}

var (
	terminatorRuns = regexp.MustCompile(`[.!?]+`)
	codeFences     = regexp.MustCompile("```[a-z]*\n?")
	// styleContracts is the per-style system-prompt contract, byte-for-byte
	// the TS lib's STYLE_CONTRACT; a style outside the union (a compile-time
	// impossibility in TypeScript) is a map miss reported at runtime.
	styleContracts = map[Style]string{
		StyleTldr:     "Summarize the text as ONE sentence of at most 25 words. Plain text, no preamble, no bullets.",
		StyleBullets:  "Summarize the text as 3 to 6 markdown bullets, each starting with \"- \" and covering one distinct point. No preamble, no closing remark.",
		StyleDetailed: "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.",
	}
)

// TextStats counts words / sentences / characters; tolerant of empty input.
// Chars counts UTF-16 code units, matching JS .length; strings.Fields is the
// trim-then-split-on-whitespace word count.
func TextStats(text string) Stats {
	return Stats{
		Words:     len(strings.Fields(text)),
		Sentences: len(terminatorRuns.FindAllString(text, -1)),
		Chars:     utf16Units(text),
	}
}

// BuildPromptMessages builds the [system, user] chat messages for the
// provider layer; long pastes are truncated with a visible marker and an
// unknown style yields an error instead of the TS union's compile miss.
func BuildPromptMessages(text string, style Style) ([]Message, error) {
	contract, ok := styleContracts[style]
	if !ok {
		return nil, fmt.Errorf("textsummarizer: unknown style %q", string(style))
	}
	stats := TextStats(text)
	body := text
	if stats.Chars > MaxInputChars {
		body = sliceUTF16(text, MaxInputChars) + "\n… (text truncated)"
	}
	return []Message{
		{Role: "system", Content: "You summarize text faithfully. " + contract},
		{Role: "user", Content: fmt.Sprintf(
			"Summarize the following text (%s style; %d words, %d sentences).\n\n%s",
			string(style), stats.Words, stats.Sentences, body)},
	}, nil
}

// ParseSummary cleans the model's reply into displayable summary text — any
// non-empty cleaned text is the summary; nil only when nothing survives.
func ParseSummary(text string) *string {
	cleaned := strings.TrimSpace(codeFences.ReplaceAllString(text, ""))
	if cleaned == "" {
		return nil
	}
	return &cleaned
}

// utf16Units counts UTF-16 code units in s (what JS .length returns): one
// per BMP rune, two per astral. Ranging never yields lone surrogates, so
// utf16.RuneLen's -1 case is unreachable. sliceUTF16 mirrors text.slice.
func utf16Units(s string) int {
	n := 0
	for _, r := range s {
		n += utf16.RuneLen(r)
	}
	return n
}

func sliceUTF16(s string, limit int) string {
	units := 0
	for i, r := range s {
		if units+utf16.RuneLen(r) > limit {
			return s[:i]
		}
		units += utf16.RuneLen(r)
	}
	return s
}

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 →