AI Text Summarizer — Ruby 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 Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# frozen_string_literal: true
# text-summarizer — prompt building, reply cleanup, and text stats.
#
# Language: Ruby (3.x, standard library only)
# CosmoDev polyglot showcase port of the `text-summarizer` tool, ported
# from src/lib/summarize.ts (the canonical TypeScript implementation).
#
# Ruby's Regexp and String primitives carry the TS lib almost verbatim.
# The one semantic wrinkle is chars: JS .length counts UTF-16 code units,
# so astral code points — emoji etc. — count 2, computed by walking
# codepoints; Ruby strings are character-oriented, not UTF-16.
#
# display source — part of CosmoDev's polyglot tool pages.
#
# Run: ruby ruby.rb
SUMMARY_STYLES = %w[tldr bullets detailed].freeze
# The per-style system-prompt contract, byte-for-byte the TS lib's.
STYLE_CONTRACT = {
"tldr" =>
"Summarize the text as ONE sentence of at most 25 words. Plain text, no preamble, no bullets.",
"bullets" =>
"Summarize the text as 3 to 6 markdown bullets, each starting with \"- \" and covering one " \
"distinct point. No preamble, no closing remark.",
"detailed" =>
"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.",
}.freeze
# Input cap: longer pastes are cut (and marked) before reaching the model.
MAX_INPUT_CHARS = 12000
# Width of one code point in UTF-16 code units (2 for astral, else 1) —
# the JS .length accounting.
def utf16_units(cp) = cp > 0xFFFF ? 2 : 1
# JS text.length: the UTF-16 code unit count of text.
def utf16_length(text) = text.each_codepoint.sum { |cp| utf16_units(cp) }
# Count words / sentences / characters; tolerant of empty input. Sentences
# count TERMINATOR runs ([.!?]+), never the quadratic body regex, the trap
# the TS lib's comment documents; String#split matches the JS
# trim-then-split-on-whitespace word count ([] = 0 words for empty input).
def text_stats(text)
{
words: text.split.length,
sentences: text.scan(/[.!?]+/).length,
chars: utf16_length(text),
}
end
# Cut to the first MAX_INPUT_CHARS UTF-16 code units, marking the cut.
def truncate(text)
units = 0
text.each_char.with_index do |ch, i|
return text[0, i] + "\n… (text truncated)" if units + utf16_units(ch.ord) > MAX_INPUT_CHARS
units += utf16_units(ch.ord)
end
text
end
# Build the [system, user] chat messages for the provider layer; long
# pastes are cut (in UTF-16 units, like JS slice) with a visible marker.
# Raises ArgumentError on a style outside SUMMARY_STYLES (the TS union type
# makes that state unrepresentable; Ruby raises instead).
def build_prompt_messages(text, style = "tldr")
raise ArgumentError, "unknown style: #{style}" unless STYLE_CONTRACT.key?(style)
stats = text_stats(text)
body = utf16_length(text) > MAX_INPUT_CHARS ? truncate(text) : text
[
{ role: "system", content: "You summarize text faithfully. #{STYLE_CONTRACT[style]}" },
{
role: "user",
content: "Summarize the following text (#{style} style; " \
"#{stats[:words]} words, #{stats[:sentences]} sentences).\n\n#{body}",
},
]
end
# Clean the model's reply into displayable summary text — any non-empty
# cleaned text is the summary; nil only when nothing survives.
def parse_summary(text)
cleaned = text.gsub(/```[a-z]*\n?/, "").strip
cleaned.empty? ? nil : cleaned
end
if $PROGRAM_NAME == __FILE__
pp text_stats("Hello world. Hi! Am I tidy? ")
build_prompt_messages("paste here").each { |m| puts "#{m[:role]}: #{m[:content]}" }
puts parse_summary("```text\nthe summary\n```").inspect # "the summary"
puts parse_summary(" \n").inspect # nil
begin
build_prompt_messages("x", "haiku")
rescue ArgumentError => e
puts e.message
end
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 →