|
| 1 | +import axios from "axios"; |
| 2 | +import TranslateEngine, { TranslateOptions, TranslateResult } from "./base"; |
| 3 | +import { Config } from "~/core"; |
| 4 | + |
| 5 | +export default class OpenAITranslate extends TranslateEngine { |
| 6 | + apiRoot = "https://api.openai.com"; |
| 7 | + systemPrompt = "You are a professional translation engine. Please translate text without explanation."; |
| 8 | + |
| 9 | + async translate(options: TranslateOptions) { |
| 10 | + let apiKey = Config.openaiApiKey; |
| 11 | + let apiRoot = this.apiRoot; |
| 12 | + if (Config.openaiApiRoot) apiRoot = Config.openaiApiRoot.replace(/\/$/, ""); |
| 13 | + let model = Config.openaiApiModel; |
| 14 | + |
| 15 | + const response = await axios.post( |
| 16 | + `${apiRoot}/v1/chat/completions`, |
| 17 | + { |
| 18 | + model, |
| 19 | + temperature: 0, |
| 20 | + max_tokens: 1000, |
| 21 | + top_p: 1, |
| 22 | + frequency_penalty: 1, |
| 23 | + presence_penalty: 1, |
| 24 | + messages: [ |
| 25 | + { |
| 26 | + role: "system", |
| 27 | + content: this.systemPrompt, |
| 28 | + }, |
| 29 | + { |
| 30 | + role: "user", |
| 31 | + content: this.generateUserPrompts(options), |
| 32 | + }, |
| 33 | + ], |
| 34 | + }, |
| 35 | + { |
| 36 | + headers: { |
| 37 | + "Content-Type": "application/json", |
| 38 | + Authorization: `Bearer ${apiKey}`, |
| 39 | + }, |
| 40 | + } |
| 41 | + ); |
| 42 | + |
| 43 | + return this.transform(response, options); |
| 44 | + } |
| 45 | + |
| 46 | + transform(response: any, options: TranslateOptions): TranslateResult { |
| 47 | + const { text, from = "auto", to = "auto" } = options; |
| 48 | + |
| 49 | + const translatedText = response.data.choices[0].message.content?.trim(); |
| 50 | + |
| 51 | + const r: TranslateResult = { |
| 52 | + text, |
| 53 | + to, |
| 54 | + from, |
| 55 | + response, |
| 56 | + result: translatedText ? [translatedText] : undefined, |
| 57 | + linkToResult: "", |
| 58 | + }; |
| 59 | + |
| 60 | + |
| 61 | + return r; |
| 62 | + } |
| 63 | + |
| 64 | + generateUserPrompts(options: TranslateOptions): string { |
| 65 | + const sourceLang = options.from; |
| 66 | + const targetLang = options.to; |
| 67 | + |
| 68 | + let generatedUserPrompt = `translate from ${sourceLang} to ${targetLang}:\n\n${options.text}`; |
| 69 | + |
| 70 | + return generatedUserPrompt; |
| 71 | + } |
| 72 | +} |
0 commit comments