Skip to content

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

// tone-rewriter — tone registry, prompt building, and reply cleanup.
//
// Language: Java (17; the top-level class is package-private so the file
//           name may differ — 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. The enum carries the registry
// and its contract sentences in one exhaustive table.
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Run: java java.java   (single-file source launch, Java 11+)

import java.util.List;

/** The five supported registers — the SSOT for the picker, in declaration
 *  order; each constant carries its wire id, label, and prompt sentence. */
enum Tone {
    PROFESSIONAL("professional", "Professional",
            "polished and businesslike, no slang, clear and direct — the register "
                    + "of a status update to stakeholders"),
    FRIENDLY("friendly", "Friendly",
            "warm and approachable, contractions welcome, like a teammate "
                    + "chatting — never stiff"),
    CONCISE("concise", "Concise",
            "as short as possible while keeping every fact; prefer one sentence; "
                    + "cut filler words without exception"),
    FORMAL("formal", "Formal",
            "ceremonial register, no contractions, complete sentences — the "
                    + "register of official correspondence"),
    PLAYFUL("playful", "Playful",
            "light and witty, a touch of humor, emojis allowed (at most two) — "
                    + "but the facts stay exact");

    final String id;
    final String label;
    final String contract;

    Tone(String id, String label, String contract) {
        this.id = id;
        this.label = label;
        this.contract = contract;
    }

    /** The registry, in order — the picker's data source. */
    static List<Tone> tones() {
        return List.of(values());
    }
}

/** tone-rewriter pure core — prompts and reply cleanup. */
final class ToneRewriter {

    /** Payload cap for the user text (the TS MAX_INPUT_CHARS). */
    static final int MAX_INPUT_CHARS = 12000;

    /** One chat message (`role` is "system" or "user"). */
    record Message(String role, String content) {}

    /**
     * Build the [system, user] chat messages for the provider layer.
     *
     * Input longer than MAX_INPUT_CHARS is sliced and tagged with a visible
     * "… (text truncated)" marker so the model knows the payload was capped.
     */
    static List<Message> buildPromptMessages(String text, Tone tone) {
        String body = text.length() > MAX_INPUT_CHARS
                ? text.substring(0, MAX_INPUT_CHARS) + "\n… (text truncated)"
                : text;
        String system = "You rewrite text in a target tone. Rewrite the user's text in a "
                + tone.id + " tone: " + tone.contract
                + ". Keep the same meaning and the same facts — only the register "
                + "changes. Output ONLY the rewritten text, no preamble, no notes.";
        return List.of(new Message("system", system), new 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; returns null only when nothing survives.
     */
    static String parseRewrite(String text) {
        String cleaned = text.replaceAll("```[a-z]*\n?", "").trim();
        return cleaned.isEmpty() ? null : cleaned;
    }

    public static void main(String[] args) {
        var msgs = buildPromptMessages("The Q3 numbers are in.", Tone.PROFESSIONAL);
        msgs.forEach(m -> System.out.println(m.role() + ": " + m.content()));

        System.out.println(parseRewrite("```text\nHere you go!\n```\n"));
        System.out.println(parseRewrite("``` \n")); // a 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 →