-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathgulp-gpt-translate.js
59 lines (47 loc) · 1.58 KB
/
gulp-gpt-translate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const through = require('through2');
const PluginError = require('plugin-error');
const { OpenAI } = require('openai');
const PLUGIN_NAME = 'gulp-gpt-translate';
function gptTranslate(options) {
if (!options || !options.apiKey) {
throw new PluginError(PLUGIN_NAME, 'An OpenAI API key is required.');
}
if (!options.targetLanguage) {
throw new PluginError(PLUGIN_NAME, 'A target language must be specified.');
}
const openai = new OpenAI();
return through.obj(function (file, enc, cb) {
const self = this;
if (file.isNull()) {
return cb(null, file); // Pass along if no contents
}
if (file.isStream()) {
self.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported.'));
return cb();
}
(async () => {
try {
const content = file.contents.toString(enc);
const response = await openai.chat.completions.create({
model: options.model || 'gpt-4o-mini',
temperature: 0,
messages: [
{
role: 'system',
content: `You are a helpful assistant that translates text to ${options.targetLanguage}. `,
},
...(options.messages || []).map((m) => ({ role: 'user', content: m })),
{ role: 'user', content },
],
});
file.contents = Buffer.from(`${response.choices[0].message.content}\n`, enc);
self.push(file);
cb();
} catch (err) {
self.emit('error', new PluginError(PLUGIN_NAME, err.message));
cb(err);
}
})();
});
}
module.exports = gptTranslate;