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# (netstandard2.0 surface, standard library only — no LINQ
//           beyond the basics, no target-typed new)
// CosmoDev polyglot showcase port of the `text-summarizer` tool, ported
// from src/lib/summarize.ts (the canonical TypeScript implementation).
//
// The CLR string is UTF-16, so string.Length IS the JS .length — chars and
// the truncation cut need no unit juggling, the least code of any port.
// Sentences count terminator runs, never the quadratic body regex, the
// trap the TS lib's comment documents.
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Build: csc csharp.cs && text-summarizer.exe   (or drop into any .NET console)

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CosmoDev.Polyglot;

/// <summary>Styles, mirroring the TS SummaryStyle union.</summary>
public static class TextSummarizer
{
    public static readonly string[] Styles = { "tldr", "bullets", "detailed" };

    /// <summary>Input cap: longer pastes are cut (and marked) before reaching the model.</summary>
    public const int MaxInputChars = 12000;

    /// <summary>Word / sentence / character counts, tolerant of empty input.</summary>
    public struct Stats
    {
        public int Words, Sentences, Chars;
    }

    /// <summary>One [role, content] chat message for the provider layer.</summary>
    public struct Message
    {
        public string Role, Content;

        public Message(string role, string content)
        {
            Role = role;
            Content = content;
        }
    }

    /// <summary>The per-style system-prompt contract, byte-for-byte the TS lib's.</summary>
    static readonly Dictionary<string, string> StyleContract = new Dictionary<string, string>
    {
        { "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." },
    };

    static readonly Regex TerminatorRuns = new Regex(@"[.!?]+", RegexOptions.Compiled);
    static readonly Regex CodeFences = new Regex("```[a-z]*\n?", RegexOptions.Compiled);

    /// <summary>
    /// 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.
    /// </summary>
    public static Stats TextStats(string text)
    {
        string trimmed = text.Trim();
        return new Stats
        {
            Words = trimmed.Length == 0 ? 0 : Regex.Split(trimmed, @"\s+").Length,
            Sentences = TerminatorRuns.Matches(text).Count,
            Chars = text.Length,
        };
    }

    /// <summary>
    /// Build the [system, user] chat messages for the provider layer; long
    /// pastes are cut at MaxInputChars UTF-16 units — exactly the JS
    /// slice(0, limit) — and marked with a visible truncation note.
    /// </summary>
    /// <exception cref="ArgumentException">on a style outside Styles — the
    /// TS union makes that state unrepresentable; C# throws instead.</exception>
    public static Message[] BuildPromptMessages(string text, string style)
    {
        string contract;
        if (!StyleContract.TryGetValue(style, out contract))
            throw new ArgumentException($"unknown style: {style}", "style");
        Stats stats = TextStats(text);
        string body = text.Length > MaxInputChars
            ? text.Substring(0, MaxInputChars) + "\n… (text truncated)"
            : text;
        return new Message[]
        {
            new Message("system", "You summarize text faithfully. " + contract),
            new Message(
                "user",
                $"Summarize the following text ({style} style; {stats.Words} words, "
                    + $"{stats.Sentences} sentences).\n\n{body}"),
        };
    }

    /// <summary>
    /// Clean the model's reply into displayable summary text — any non-empty
    /// cleaned text is the summary; null only when nothing survives.
    /// </summary>
    public static string ParseSummary(string text)
    {
        string cleaned = CodeFences.Replace(text, string.Empty).Trim();
        return cleaned.Length > 0 ? cleaned : null;
    }

    static void Main()
    {
        Stats s = TextStats("Hello world. Hi! Am I tidy?  ");
        Console.WriteLine($"words={s.Words} sentences={s.Sentences} chars={s.Chars}");

        foreach (Message m in BuildPromptMessages("paste here", "tldr"))
            Console.WriteLine($"{m.Role}: {m.Content}");

        Console.WriteLine(ParseSummary("```text\nthe summary\n```"));  // the summary
        Console.WriteLine(ParseSummary("   \n") ?? "(null)");          // (null)

        try { BuildPromptMessages("x", "haiku"); }
        catch (ArgumentException e) { Console.WriteLine(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 →