Skip to content

Instantly share code, notes, and snippets.

@atomlab
Created March 1, 2025 19:13
Show Gist options
  • Save atomlab/19ce55f47414fa9c57a9aae8816b1ea8 to your computer and use it in GitHub Desktop.
Save atomlab/19ce55f47414fa9c57a9aae8816b1ea8 to your computer and use it in GitHub Desktop.
linguist Translator OpenAI support

This gist explains how to integrate a custom OpenAI translator backend into the Linguist Chrome extension.

Source: https://github.com/translate-tools/linguist

Issue: translate-tools/linguist#230 (comment)

Go to Setting -> Custom translators -> Add

class OpenAITranslator {
    constructor() {
        this.apiKey = "API_KEY"; // Replace with your actual key
        this.endpoint = "https://api.openai.com/v1/chat/completions";
        this.model = "gpt-4o-mini"; // You can change it to "gpt-3.5-turbo" if you prefer
        this.defaultPrompt = "You are a professional foreign language translator. Your task is to translate the text from ${from} to ${to}, preserving the original meaning, style, and tone. If the text contains idioms or cultural references, adapt them to be understandable for native speakers of the target language. Translate accurately and naturally, without unnecessary changes unless required.";  
    }

    async translate(text, from, to = "en") {
        const response = await this.fetchTranslation(text, from, to);
        return response || text;
    }

    async translateBatch(texts, from, to = "en") {
        return Promise.all(texts.map(text => this.translate(text, from, to)));
    }

    getLengthLimit() {
        return 4000;
    }

    getRequestsTimeout() {
        return 500;
    }

    checkLimitExceeding(text) {
        return text.length > this.getLengthLimit() ? text.length - this.getLengthLimit() : 0;
    }

    static isSupportedAutoFrom() {
        return true;
    }

    static getSupportedLanguages() {
        return ['en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'zh', 'ja', 'ko'];
    }

    async fetchTranslation(text, from, to) {
        try {
            const response = await fetch(this.endpoint, {
                method: "POST",
                headers: {
                    "Authorization": `Bearer ${this.apiKey}`,
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    model: this.model,
                    messages: [
                        { role: "system", content: this.defaultPrompt },
                        { role: "user", content: `Translate from ${from} to ${to}: ${text}` }
                    ],
                    max_tokens: 1000,
                    temperature: 0.3
                })
            });

            const data = await response.json();
            return data.choices?.[0]?.message?.content.trim();
        } catch (error) {
            console.error("Translation error:", error);
            return null;
        }
    }
}

OpenAITranslator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment