Skip to content

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

// text-summarizer — prompt building, reply cleanup, and text stats.
//
// Language: C++ (C++17, standard library only)
// CosmoDev polyglot showcase port of the `text-summarizer` tool, ported from
// src/lib/summarize.ts (the canonical TypeScript implementation).
//
// std::regex carries the TS lib's two patterns (fence stripper, terminator
// runs — counting runs, never the quadratic body regex). chars counts UTF-16
// code units so astral characters count 2, exactly like JS .length; multi-
// byte UTF-8 never contains ASCII bytes, so byte-wise scans are safe.
//
// Build: c++ -std=c++17 cpp.cpp && ./a.out

#include <algorithm>
#include <optional>
#include <regex>
#include <string>
#include <vector>

namespace textsummarizer {

/// Summary styles mirror the SummaryStyle union in the TS lib.
enum class Style { Tldr, Bullets, Detailed };

/// Input cap: longer pastes are cut (and marked) before reaching the model.
constexpr std::size_t kMaxInputChars = 12000;

/// One [role, content] chat message for the provider layer.
struct Message {
    std::string role;
    std::string content;
};

/// Wire name of a style, as in the TS union ('tldr' | 'bullets' | 'detailed').
inline const char* styleName(Style style) {
    switch (style) {
    case Style::Bullets:  return "bullets";
    case Style::Detailed: return "detailed";
    default:              return "tldr";
    }
}

/// Per-style system-prompt contract, byte-for-byte the TS STYLE_CONTRACT.
inline const char* styleContract(Style style) {
    switch (style) {
    case Style::Tldr:
        return "Summarize the text as ONE sentence of at most 25 words. "
               "Plain text, no preamble, no bullets.";
    case Style::Bullets:
        return "Summarize the text as 3 to 6 markdown bullets, each starting "
               "with \"- \" and covering one distinct point. No preamble, no "
               "closing remark.";
    default:
        return "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.
struct TextStats {
    std::size_t words = 0;
    std::size_t sentences = 0;
    std::size_t chars = 0;  // UTF-16 code units, like JS .length
};

namespace {

/// The six whitespace characters JavaScript's \s matches in the ASCII range.
inline bool isSpace(char c) {
    return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' ||
           c == '\r';
}

/// Byte length of the UTF-8 sequence led by b (stray bytes ride as one).
inline std::size_t utf8Len(unsigned char b) {
    if ((b & 0x80) == 0) return 1;
    if ((b & 0xE0) == 0xC0) return 2;
    if ((b & 0xF0) == 0xE0) return 3;
    return (b & 0xF8) == 0xF0 ? 4 : 1;
}

/// UTF-16 width of the code point in an n-byte UTF-8 sequence: 4-byte
/// sequences are exactly the astral plane, which JS .length counts as 2.
inline std::size_t utf16Width(std::size_t n) { return n == 4 ? 2 : 1; }

}  // namespace

/**
 * Count words / sentences / characters; tolerant of empty input. Sentences
 * count TERMINATOR runs (the body regex is quadratic on such input — the
 * trap documented in the TS lib); chars counts UTF-16 units like JS .length.
 */
inline TextStats textStats(const std::string& text) {
    static const std::regex kTerminators("[.!?]+");
    TextStats st;
    bool inWord = false;
    for (char c : text) {
        if (isSpace(c)) {
            inWord = false;
        } else if (!inWord) {
            inWord = true;
            ++st.words;  // trim().split(/\s+/), in one pass
        }
    }
    const auto begin = std::sregex_iterator(text.begin(), text.end(), kTerminators);
    st.sentences = static_cast<std::size_t>(
        std::distance(begin, std::sregex_iterator()));
    for (std::size_t i = 0; i < text.size();) {
        st.chars += utf16Width(reinterpret_cast<const unsigned char*>(&text[i]),
                               utf8Len(static_cast<unsigned char>(text[i])));
        i += utf8Len(static_cast<unsigned char>(text[i]));
    }
    return st;
}

/// The TS text.slice(0, limit) with a UTF-16 unit budget, so the cut lands
/// between runes.
inline std::string sliceUtf16(const std::string& text, std::size_t limit) {
    std::size_t units = 0, i = 0;
    while (i < text.size()) {
        const std::size_t n = utf8Len(static_cast<unsigned char>(text[i]));
        const std::size_t w =
            utf16Width(reinterpret_cast<const unsigned char*>(&text[i]), n);
        if (units + w > limit) break;
        units += w;
        i += n;
    }
    return text.substr(0, i);
}

/**
 * Build the [system, user] chat messages for the provider layer; long pastes
 * are truncated with a visible marker.
 */
inline std::vector<Message> buildPromptMessages(const std::string& text,
                                                Style style) {
    const TextStats st = textStats(text);
    const std::string body =
        st.chars > kMaxInputChars
            ? sliceUtf16(text, kMaxInputChars) + "\n… (text truncated)"
            : text;
    return {
        {"system",
         std::string("You summarize text faithfully. ") + styleContract(style)},
        {"user", "Summarize the following text (" + std::string(styleName(style)) +
                 " style; " + std::to_string(st.words) + " words, " +
                 std::to_string(st.sentences) + " sentences).\n\n" + body},
    };
}

/**
 * Clean the model's reply into displayable summary text — any non-empty
 * cleaned text is the summary; nullopt only when nothing survives.
 */
inline std::optional<std::string> parseSummary(const std::string& text) {
    static const std::regex kFence(R"(```[a-z]*\n?)");
    std::string cleaned = std::regex_replace(text, kFence, "");
    // trim() — both ends, the six whitespace characters.
    const auto notSpace = [](char c) { return !isSpace(c); };
    cleaned.erase(cleaned.begin(), std::find_if(cleaned.begin(), cleaned.end(), notSpace));
    cleaned.erase(std::find_if(cleaned.rbegin(), cleaned.rend(), notSpace).base(), cleaned.end());
    if (cleaned.empty()) return std::nullopt;
    return cleaned;
}

}  // namespace textsummarizer

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 →