AI Tone Rewriter — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* tone-rewriter — tone registry, prompt building, and reply cleanup.
*
* Language: PHP 7.4+ (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. PHP's preg_replace covers the fence
* cleanup in one call; mb_* keeps the truncation marker from splitting a
* multibyte character.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
/** Payload cap for the user text (mirrors the TS MAX_INPUT_CHARS). */
const MAX_INPUT_CHARS = 12000;
/**
* The five supported registers — the SSOT for the UI's segmented control.
* Each entry mirrors the TS `ToneOption` shape: { id, label }.
*/
const TONES = [
['id' => 'professional', 'label' => 'Professional'],
['id' => 'friendly', 'label' => 'Friendly'],
['id' => 'concise', 'label' => 'Concise'],
['id' => 'formal', 'label' => 'Formal'],
['id' => 'playful', 'label' => 'Playful'],
];
/**
* Per-tone register sentence embedded in the system prompt.
*
* @var array<string, string>
*/
const TONE_CONTRACT = [
'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',
];
/**
* Build the [system, user] chat messages for the provider layer.
*
* Each message mirrors the TS { role, content } shape. Input longer than
* MAX_INPUT_CHARS is sliced and tagged with a visible "… (text truncated)"
* marker so the model knows the payload was capped. mb_strlen / mb_substr
* count code points where the TS lib counts UTF-16 units — they agree for
* everything outside the astral planes.
*
* @param string $tone One of the TONES ids (the TS `Tone` union).
* @throws \InvalidArgumentException when $tone is not a supported register —
* the runtime stand-in for the TS union type check.
*/
function build_prompt_messages(string $text, string $tone): array
{
if (!isset(TONE_CONTRACT[$tone])) {
throw new InvalidArgumentException("unsupported tone: {$tone}");
}
$body = mb_strlen($text) > MAX_INPUT_CHARS
? mb_substr($text, 0, MAX_INPUT_CHARS) . "\n… (text truncated)"
: $text;
return [
[
'role' => 'system',
'content' => "You rewrite text in a target tone. Rewrite the user's text in a {$tone} 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.',
],
['role' => 'user', 'content' => $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; null only when nothing survives.
*/
function parse_rewrite(string $text): ?string
{
$cleaned = trim((string) preg_replace('/```[a-z]*\n?/', '', $text));
return $cleaned !== '' ? $cleaned : null;
}
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 →