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++ (C++17, standard library only — std::regex carries the fence
//           cleanup, std::optional carries the "null when nothing survives")
// 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. std::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.
//
// Build: c++ -std=c++17 cpp.cpp && ./a.out

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

/// The five supported registers (the TS `Tone` string-literal union).
enum class Tone { Professional, Friendly, Concise, Formal, Playful };

/// A registry entry — the TS `ToneOption` (wire id + human label).
struct ToneOption {
    const char *id;
    const char *label;
};

/// The five-register registry — the SSOT for the picker, in order.
inline const std::vector<ToneOption> &tones()
{
    static const std::vector<ToneOption> t = {
        { "professional", "Professional" },
        { "friendly",     "Friendly"     },
        { "concise",      "Concise"      },
        { "formal",       "Formal"       },
        { "playful",      "Playful"      },
    };
    return t;
}

/// Per-tone register sentence embedded in the system prompt.
inline const char *tone_contract(Tone tone)
{
    switch (tone) {
    case Tone::Professional:
        return "polished and businesslike, no slang, clear and direct — the "
               "register of a status update to stakeholders";
    case Tone::Friendly:
        return "warm and approachable, contractions welcome, like a teammate "
               "chatting — never stiff";
    case Tone::Concise:
        return "as short as possible while keeping every fact; prefer one "
               "sentence; cut filler words without exception";
    case Tone::Formal:
        return "ceremonial register, no contractions, complete sentences — "
               "the register of official correspondence";
    case Tone::Playful:
        return "light and witty, a touch of humor, emojis allowed (at most "
               "two) — but the facts stay exact";
    }
    return "";
}

/// Payload cap for the user text (the TS `MAX_INPUT_CHARS`).
constexpr std::size_t kMaxInputChars = 12000;

/// One chat message (`role` is "system" or "user").
struct Message {
    std::string role;
    std::string content;
};

/// Build the [system, user] chat messages for the provider layer.
///
/// std::string::size() counts bytes where the TS lib counts UTF-16 units —
/// they agree for everything outside the astral planes. Input over the cap
/// is sliced and tagged with a visible "… (text truncated)" marker.
inline std::vector<Message> build_prompt_messages(const std::string &text,
                                                  Tone tone)
{
    const std::string body =
        text.size() > kMaxInputChars
            ? text.substr(0, kMaxInputChars) + "\n… (text truncated)"
            : text;
    const std::string system =
        std::string("You rewrite text in a target tone. Rewrite the user's "
                    "text in a ") +
        tones()[static_cast<std::size_t>(tone)].id + " tone: " +
        tone_contract(tone) +
        ". Keep the same meaning and the same facts — only the register "
        "changes. Output ONLY the rewritten text, no preamble, no notes.";
    return { Message{"system", system}, Message{"user", body} };
}

/**
 * Clean the model's reply into displayable rewritten text.
 *
 * Strips every ```lang fence marker (the TS /```[a-z]*\n?/g regex) plus
 * surrounding whitespace. No strict format contract — any non-empty cleaned
 * text is the rewrite; std::nullopt only when nothing survives.
 */
inline std::optional<std::string> parse_rewrite(const std::string &text)
{
    static const std::regex fence("```[a-z]*\n?");
    const std::string stripped = std::regex_replace(text, fence, "");

    const std::string space = " \t\n\v\f\r";
    const auto first = stripped.find_first_not_of(space);
    if (first == std::string::npos) return std::nullopt;
    const auto last = stripped.find_last_not_of(space);
    return stripped.substr(first, last - first + 1);
}

int main()
{
    const auto msgs = build_prompt_messages("The Q3 numbers are in.",
                                            Tone::Professional);
    std::printf("system: %.72s...\nuser: %s\n", msgs[0].content.c_str(),
                msgs[1].content.c_str());

    const auto rewrite = parse_rewrite("```text\nHere you go!\n```\n");
    std::printf("cleaned: %s\n", rewrite ? rewrite->c_str() : "(null)");

    const auto empty = parse_rewrite("``` \n"); // a fence and nothing else
    std::printf("empty reply: %s\n", empty ? empty->c_str() : "(null)");
    return 0;
}

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 →