Skip to content

AI Tone Rewriter — C# source

Rewrite any message in a new tone — professional, friendly, concise, formal, or playful — with 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.

// tone-rewriter — tone registry, prompt building, and reply cleanup.
//
// Language: C# (netstandard2.0 surface — no records, no switch expressions;
//           Regex carries the fence cleanup and string.Length already counts
//           UTF-16 units exactly like the TS lib)
// CosmoDev polyglot showcase port of the `tone-rewriter` tool, ported from
// src/lib/tone-rewriter.ts (the canonical TypeScript implementation).
//
// Why this file exists: the tone rewriter is an AI tool, but its contract is
// pure — which registers exist, how the system prompt is assembled, and how
// a raw model reply is cleaned for display. Regex is the only machinery the
// cleanup needs, the same role re.sub plays in this tool's python.py.
//
// display source — part of CosmoDev's polyglot tool pages.

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

namespace CosmoDev.Polyglot
{
    /// <summary>The five supported registers (the TS `Tone` string union).</summary>
    public enum Tone
    {
        Professional,
        Friendly,
        Concise,
        Formal,
        Playful,
    }

    /// <summary>tone-rewriter pure core — registry, prompts, reply cleanup.</summary>
    public static class ToneRewriter
    {
        /// <summary>Payload cap for the user text (the TS MAX_INPUT_CHARS).</summary>
        public const int MaxInputChars = 12000;

        /// <summary>A registry entry — the TS `ToneOption`.</summary>
        public sealed class ToneOption
        {
            public readonly string Id;
            public readonly string Label;

            public ToneOption(string id, string label)
            {
                Id = id;
                Label = label;
            }
        }

        /// <summary>The five-register registry — the SSOT for the picker, in order.</summary>
        public static readonly ToneOption[] Tones =
        {
            new ToneOption("professional", "Professional"),
            new ToneOption("friendly", "Friendly"),
            new ToneOption("concise", "Concise"),
            new ToneOption("formal", "Formal"),
            new ToneOption("playful", "Playful"),
        };

        /// <summary>Per-tone register sentence embedded in the system prompt.</summary>
        static readonly string[] Contracts =
        {
            "polished and businesslike, no slang, clear and direct — the register " +
            "of a status update to stakeholders",
            "warm and approachable, contractions welcome, like a teammate " +
            "chatting — never stiff",
            "as short as possible while keeping every fact; prefer one sentence; " +
            "cut filler words without exception",
            "ceremonial register, no contractions, complete sentences — the " +
            "register of official correspondence",
            "light and witty, a touch of humor, emojis allowed (at most two) — " +
            "but the facts stay exact",
        };

        /// <summary>One chat message (`role` is "system" or "user").</summary>
        public sealed class Message
        {
            public readonly string Role;
            public readonly string Content;

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

        /// <summary>
        /// Build the [system, user] chat messages for the provider layer.
        /// Input longer than <see cref="MaxInputChars"/> is sliced and tagged
        /// with a visible "… (text truncated)" marker.
        /// </summary>
        public static IList<Message> BuildPromptMessages(string text, Tone tone)
        {
            string body = text.Length > MaxInputChars
                ? text.Substring(0, MaxInputChars) + "\n… (text truncated)"
                : text;
            string system =
                "You rewrite text in a target tone. Rewrite the user's text in a " +
                Tones[(int)tone].Id + " tone: " + Contracts[(int)tone] +
                ". Keep the same meaning and the same facts — only the register " +
                "changes. Output ONLY the rewritten text, no preamble, no notes.";
            return new List<Message>
            {
                new Message("system", system),
                new Message("user", body),
            };
        }

        /// <summary>The TS /```[a-z]*\n?/g fence marker, compiled once.</summary>
        static readonly Regex Fence = new Regex("```[a-z]*\n?", RegexOptions.Compiled);

        /// <summary>
        /// Clean the model's reply into displayable rewritten text. Strips
        /// every ```lang fence marker plus surrounding whitespace; returns
        /// null only when nothing survives.
        /// </summary>
        public static string ParseRewrite(string text)
        {
            string cleaned = Fence.Replace(text, string.Empty).Trim();
            return cleaned.Length > 0 ? cleaned : null;
        }

        static void Main()
        {
            var msgs = BuildPromptMessages("The Q3 numbers are in.", Tone.Professional);
            Console.WriteLine(msgs[0].Role + ": " + msgs[0].Content);
            Console.WriteLine(msgs[1].Role + ": " + msgs[1].Content);

            Console.WriteLine(ParseRewrite("```text\nHere you go!\n```\n") ?? "(null)");
            Console.WriteLine(ParseRewrite("``` \n") ?? "(null)");  // fence and nothing else
        }
    }
}

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 →