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;