Skip to content

AI Text Translator — Go source

Translate any text between 24 languages with an LLM — auto-detected or explicit source, straight from your browser with your own free Groq key.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package texttranslator is the Go twin of CosmoDev's src/lib/translate.ts.
//
// Language: Go (standard library only).
// CosmoDev polyglot showcase port of the `text-translator` tool, ported from
// src/lib/translate.ts (the canonical TypeScript implementation).
//
// The translator island is a thin shell over a shared LLM provider, so the
// portable, testable surface is pure: the curated language list, the
// [system, user] chat-message construction, and the reply cleanup. The
// fence stripper is stdlib regexp — the same /```[a-z]*\n?/g the TS port uses.
//
// display source — part of CosmoDev's polyglot tool pages.
package texttranslator

import (
	"fmt"
	"regexp"
	"strings"
)

// AutoSource is the sentinel for "let the model detect the input language".
const AutoSource = "auto"

// Language is one entry of the curated common-language list.
type Language struct {
	ID    string
	Label string
}

// AutoLanguage is the sentinel entry shown in the "from" select.
var AutoLanguage = Language{ID: AutoSource, Label: "Auto-detect"}

// Languages is the curated common-language list — the SSOT for both selects.
var Languages = []Language{
	{"en", "English"},
	{"es", "Spanish"},
	{"fr", "French"},
	{"de", "German"},
	{"pt", "Portuguese"},
	{"it", "Italian"},
	{"nl", "Dutch"},
	{"sv", "Swedish"},
	{"pl", "Polish"},
	{"tr", "Turkish"},
	{"ru", "Russian"},
	{"uk", "Ukrainian"},
	{"ar", "Arabic"},
	{"fa", "Persian"},
	{"he", "Hebrew"},
	{"hi", "Hindi"},
	{"bn", "Bengali"},
	{"zh", "Chinese"},
	{"ja", "Japanese"},
	{"ko", "Korean"},
	{"vi", "Vietnamese"},
	{"th", "Thai"},
	{"id", "Indonesian"},
	{"sw", "Swahili"},
}

// maxInputChars caps translated input; longer text is cut and marked.
const maxInputChars = 12000

// ChatMessage is one message for the provider layer; Role is "system"/"user".
type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

// fenceRe mirrors the TS port's replace-all regex: /```[a-z]*\n?/g.
var fenceRe = regexp.MustCompile("```[a-z]*\n?")

// languageLabel returns the label for a known language id; unknown ids pass
// through unchanged, exactly like the TS lib's `?? id` fallback.
func languageLabel(id string) string {
	for _, l := range Languages {
		if l.ID == id {
			return l.Label
		}
	}
	return id
}

// BuildPromptMessages builds the [system, user] chat messages for the
// provider layer. from is AutoSource or a Languages id; to is a Languages id.
// Inputs longer than maxInputChars runes are cut and marked so the model
// knows the text ends early (code points; the TS slice counts UTF-16 units).
func BuildPromptMessages(text, from, to string) []ChatMessage {
	fromPart := fmt.Sprintf("The source language is %s.", languageLabel(from))
	if from == AutoSource {
		fromPart = "Detect the source language yourself."
	}

	body := text
	if runes := []rune(text); len(runes) > maxInputChars {
		body = string(runes[:maxInputChars]) + "\n… (text truncated)"
	}

	system := fmt.Sprintf(
		"You are a faithful translator. %s Translate the user's text into %s. "+
			"Output ONLY the translation — no preamble, no notes, no backticks, "+
			"preserving paragraphs, formatting, and code blocks as-is.",
		fromPart, languageLabel(to),
	)
	return []ChatMessage{
		{Role: "system", Content: system},
		{Role: "user", Content: body},
	}
}

// ParseTranslation cleans the model's reply into displayable translation
// text. No strict format contract — any non-empty cleaned text is the
// translation; ok is false only when nothing survives (the TS port's null).
func ParseTranslation(text string) (string, bool) {
	cleaned := strings.TrimSpace(fenceRe.ReplaceAllString(text, ""))
	if cleaned == "" {
		return "", false
	}
	return cleaned, true
}

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 →