Skip to content

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

// Package tonerewriter is the Go twin of CosmoDev's src/lib/tone-rewriter.ts.
//
// Language: Go (standard library only).
// 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 fence cleanup needs no regexp
// import: strings.Index + TrimPrefix reproduce the TS /```[a-z]*\n?/g scan.
//
// display source — part of CosmoDev's polyglot tool pages.
package tonerewriter

import (
	"strings"
	"unicode/utf8"
)

// Tone is one of the five supported registers (the TS `Tone` string union).
type Tone string

const (
	Professional Tone = "professional"
	Friendly     Tone = "friendly"
	Concise      Tone = "concise"
	Formal       Tone = "formal"
	Playful      Tone = "playful"
)

// ToneOption pairs a register with its human label (the TS `ToneOption`).
type ToneOption struct {
	ID    Tone
	Label string
}

// Tones is the five-register registry — the SSOT for the picker, in order.
var Tones = []ToneOption{
	{Professional, "Professional"},
	{Friendly, "Friendly"},
	{Concise, "Concise"},
	{Formal, "Formal"},
	{Playful, "Playful"},
}

// MaxInputChars caps the user text sent to the provider (TS MAX_INPUT_CHARS).
const MaxInputChars = 12000

// Message is one chat message ("system" or "user" role).
type Message struct {
	Role    string
	Content string
}

// BuildPromptMessages builds the [system, user] chat messages for the
// provider layer. Go twin of buildPromptMessages(). User text longer than
// MaxInputChars is sliced and tagged with a visible "… (text truncated)"
// marker so the model knows the payload was capped. The cut counts runes
// (code points) where the TS lib counts UTF-16 units — they agree for
// everything outside the astral planes.
func BuildPromptMessages(text string, tone Tone) []Message {
	body := text
	if utf8.RuneCountInString(text) > MaxInputChars {
		body = string([]rune(text)[:MaxInputChars]) + "\n… (text truncated)"
	}
	return []Message{
		{
			Role: "system",
			Content: "You rewrite text in a target tone. Rewrite the user's text in a " +
				string(tone) + " tone: " + toneContract[tone] +
				". Keep the same meaning and the same facts — only the register changes. Output ONLY the rewritten text, no preamble, no notes.",
		},
		{Role: "user", Content: body},
	}
}

// ParseRewrite cleans the model's reply into displayable rewritten text. Go
// twin of parseRewrite(): the bool result is false exactly when the TS
// returns null (nothing survives fence stripping + trimming).
func ParseRewrite(text string) (string, bool) {
	cleaned := strings.TrimSpace(stripFences(text))
	if cleaned == "" {
		return "", false
	}
	return cleaned, true
}

// stripFences removes every "```lang" fence marker — an optional lowercase
// language tag plus one optional newline — mirroring the TS /```[a-z]*\n?/g
// regex. Lone backtick runs shorter than three are kept as-is.
func stripFences(s string) string {
	var b strings.Builder
	b.Grow(len(s))
	for {
		i := strings.Index(s, "```")
		if i < 0 {
			break
		}
		b.WriteString(s[:i])
		s = s[i+3:]
		j := 0
		for j < len(s) && s[j] >= 'a' && s[j] <= 'z' {
			j++
		}
		s = strings.TrimPrefix(s[j:], "\n")
	}
	b.WriteString(s)
	return b.String()
}

// toneContract is the per-tone register sentence embedded in the system
// prompt, keyed by Tone exactly like the TS TONE_CONTRACT table.
var toneContract = map[Tone]string{
	Professional: "polished and businesslike, no slang, clear and direct — the register of a status update to stakeholders",
	Friendly:     "warm and approachable, contractions welcome, like a teammate chatting — never stiff",
	Concise:      "as short as possible while keeping every fact; prefer one sentence; cut filler words without exception",
	Formal:       "ceremonial register, no contractions, complete sentences — the register of official correspondence",
	Playful:      "light and witty, a touch of humor, emojis allowed (at most two) — but the facts stay exact",
}

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 →