-
Notifications
You must be signed in to change notification settings - Fork 0
/
openaiApi.js
48 lines (42 loc) · 1.3 KB
/
openaiApi.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
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const openaiApi = axios.create({
baseURL: 'https://api.openai.com/v1',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json'
}
});
export async function translateText(text, targetLanguage) {
try {
const response = await openaiApi.post('/chat/completions', {
model: 'gpt-4o',
messages: [{
role: 'system',
content: `Translate the following text to ${targetLanguage} and give me markdown all in code fences: ${text}`
}]
});
const translation = response.data.choices[0].message.content;
return translation.replace("```markdown", "").replaceAll("```", "");
} catch (error) {
console.error('Error translating text:', error);
throw error;
}
}
export async function translateTitle(text, targetLanguage) {
try {
const response = await openaiApi.post('/chat/completions', {
model: 'gpt-4o',
messages: [{
role: 'system',
content: `Translate the following title to ${targetLanguage} and only print the translation: ${text}`
}]
});
const translation = response.data.choices[0].message.content;
return translation.replace("```markdown", "").replaceAll("```", "");
} catch (error) {
console.error('Error translating text:', error);
throw error;
}
}