Skip to content

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

//! text-summarizer — prompt building, reply cleanup, and text stats.
//!
//! Language: Zig (0.13, standard library only)
//! CosmoDev polyglot showcase port of the `text-summarizer` tool, ported
//! from src/lib/summarize.ts (the canonical TypeScript implementation).
//!
//! The TS lib's regexes become byte scans: terminator runs (counted, never
//! matched — the body regex is quadratic on terminator-free input) and a
//! hand-rolled fence stripper. chars counts UTF-16 code units so astral
//! characters count 2, exactly like JS .length; multi-byte UTF-8 never
//! contains ASCII bytes, so the byte scans are UTF-8 safe. Style is an
//! enum, so the TS union's "unknown style" is unrepresentable.
//!
//! Test: zig test zig.zig

const std = @import("std");

/// Summary styles, mirroring the TS SummaryStyle union.
pub const Style = enum { tldr, bullets, detailed };

/// Input cap: longer pastes are cut (and marked) before reaching the model.
pub const max_input_chars: usize = 12000;

/// Word / sentence / character counts, tolerant of empty input. chars is
/// UTF-16 code units, like JS .length.
pub const Stats = struct { words: usize, sentences: usize, chars: usize };

/// One [role, content] chat message for the provider layer.
pub const Message = struct { role: []const u8, content: []const u8 };

/// The per-style system-prompt contract, byte-for-byte the TS lib's.
pub fn styleContract(style: Style) []const u8 {
    return switch (style) {
        .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.",
    };
}

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

/// Count words / sentences / characters; tolerant of empty input. The six
/// \s whitespace bytes are all ASCII, so the single-pass byte scans are
/// UTF-8 safe: word starts (trim().split(/\s+/)) and terminator runs
/// ([.!?]+); chars is UTF-16 units — astral (4-byte) sequences count 2,
/// like JS .length.
pub fn textStats(text: []const u8) Stats {
    var st = Stats{ .words = 0, .sentences = 0, .chars = 0 };
    var in_word = false;
    var in_run = false;
    var i: usize = 0;
    while (i < text.len) {
        const b = text[i];
        const n = utf8Len(b);
        if (std.ascii.isWhitespace(b)) {
            in_word = false;
        } else if (!in_word) {
            in_word = true;
            st.words += 1;
        }
        const stop = b == '.' or b == '!' or b == '?';
        if (stop and !in_run) st.sentences += 1;
        in_run = stop;
        st.chars += if (n == 4) @as(usize, 2) else 1;
        i += n;
    }
    return st;
}

/// The TS text.slice(0, limit) with a UTF-16 unit budget, so the cut lands
/// between sequences.
fn sliceUtf16(text: []const u8, limit: usize) []const u8 {
    var units: usize = 0;
    var i: usize = 0;
    while (i < text.len) {
        const n = utf8Len(text[i]);
        if (units + (if (n == 4) @as(usize, 2) else 1) > limit) return text[0..i];
        units += if (n == 4) @as(usize, 2) else 1;
        i += n;
    }
    return text;
}

/// Build the [system, user] chat messages for the provider layer; long
/// pastes are truncated with a visible marker. Caller owns the returned
/// slice and both content strings.
pub fn buildPromptMessages(
    allocator: std.mem.Allocator,
    text: []const u8,
    style: Style,
) error{OutOfMemory}![]Message {
    const st = textStats(text);
    const truncated = st.chars > max_input_chars;
    const body = if (truncated)
        try std.fmt.allocPrint(allocator, "{s}\n… (text truncated)", .{sliceUtf16(text, max_input_chars)})
    else
        text;
    errdefer if (truncated) allocator.free(body);

    const messages = try allocator.alloc(Message, 2);
    errdefer allocator.free(messages);
    messages[0] = .{
        .role = "system",
        .content = try std.fmt.allocPrint(allocator, "You summarize text faithfully. {s}", .{styleContract(style)}),
    };
    messages[1] = .{
        .role = "user",
        .content = try std.fmt.allocPrint(
            allocator,
            "Summarize the following text ({s} style; {d} words, {d} sentences).\n\n{s}",
            .{ @tagName(style), st.words, st.sentences, body },
        ),
    };
    return messages;
}

/// Clean the model's reply into displayable summary text — any non-empty
/// cleaned text is the summary; null only when nothing survives. Caller
/// owns the returned slice.
pub fn parseSummary(allocator: std.mem.Allocator, text: []const u8) error{OutOfMemory}!?[]u8 {
    const out = try allocator.alloc(u8, text.len);
    errdefer allocator.free(out);

    // Drop every /```[a-z]*\n?/ match: "```" opens a fence, optional
    // lowercase letters name the language, one optional newline ends it.
    var o: usize = 0;
    var i: usize = 0;
    while (i < text.len) {
        if (i + 3 <= text.len and std.mem.eql(u8, text[i .. i + 3], "```")) {
            i += 3;
            while (i < text.len and text[i] >= 'a' and text[i] <= 'z') i += 1;
            if (i < text.len and text[i] == '\n') i += 1;
        } else {
            out[o] = text[i];
            o += 1;
            i += 1;
        }
    }

    // trim() — both ends; never a zero-length summary (null instead), so
    // dupe the survivor and free the scratch.
    var start: usize = 0;
    var end: usize = o;
    while (start < end and std.ascii.isWhitespace(out[start])) start += 1;
    while (end > start and std.ascii.isWhitespace(out[end - 1])) end -= 1;
    if (start == end) {
        allocator.free(out);
        return null;
    }
    const cleaned = try allocator.dupe(u8, out[start..end]);
    allocator.free(out);
    return cleaned;
}

test "textStats matches the TS lib, including the UTF-16 chars contract" {
    const t = std.testing;
    try t.expectEqual(Stats{ .words = 0, .sentences = 0, .chars = 0 }, textStats(""));
    try t.expectEqual(Stats{ .words = 6, .sentences = 3, .chars = 29 }, textStats("Hello world. Hi! Am I tidy?  "));
    // 🌍 is astral: 4 UTF-8 bytes but 2 UTF-16 units, like JS .length.
    try t.expectEqual(Stats{ .words = 1, .sentences = 0, .chars = 3 }, textStats("a🌍"));
}

test "parseSummary and buildPromptMessages match the TS lib" {
    const t = std.testing;
    const a = t.allocator;

    const s = (try parseSummary(a, "```text\nthe summary\n```")).?;
    defer a.free(s);
    try t.expectEqualStrings("the summary", s);
    try t.expectEqual(@as(?[]u8, null), try parseSummary(a, "```\n\n"));

    const msgs = try buildPromptMessages(a, "One. Two", .tldr);
    defer {
        a.free(msgs[0].content);
        a.free(msgs[1].content);
        a.free(msgs);
    }
    try t.expectEqualStrings("system", msgs[0].role);
    try t.expect(std.mem.startsWith(u8, msgs[0].content, "You summarize text faithfully. "));
    try t.expect(std.mem.endsWith(u8, msgs[0].content, styleContract(.tldr)));
    try t.expectEqualStrings(
        "Summarize the following text (tldr style; 2 words, 1 sentences).\n\nOne. Two",
        msgs[1].content,
    );
}

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 →