-
Notifications
You must be signed in to change notification settings - Fork 1
/
createChatCompletion.js
70 lines (64 loc) · 1.87 KB
/
createChatCompletion.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
60
61
62
63
64
65
66
67
68
69
70
let vscode;
try {
vscode = require('vscode');
} catch (e) {
console.log("Could not load vscode");
}
const { Configuration, OpenAIApi } = require("openai");
const getOpenAIKey = async () => {
// If the API key is not set in the environment variable, try to get it from the VSCode workspace configuration
const openaiApiKey = vscode.workspace.getConfiguration().get('chadgpt.apiKey') || process.env.OPENAI_API_KEY;
if (openaiApiKey) {
return openaiApiKey;
}
const apiKey = await vscode.window.showInputBox({
prompt: 'Please enter your OpenAI API key'
});
if (apiKey) {
// Save the API key to the VSCode workspace configuration
vscode.workspace.getConfiguration().update('chadgpt.apiKey', apiKey, vscode.ConfigurationTarget.Global);
// Save the API key to the environment variable
process.env.OPENAI_API_KEY = apiKey;
return apiKey;
} else {
vscode.window.showErrorMessage('Please enter a valid OpenAI API key');
return;
}
}
const createChatCompletion = async (messages, retry=5) => {
console.log("messages: ", messages);
if (messages.length > 50) {
throw new Error("Too many messages");
}
const apiKey = await getOpenAIKey();
const configuration = new Configuration({
apiKey: apiKey,
});
const openai = new OpenAIApi(configuration);
let responseMsg;
try {
const completion = await openai.createChatCompletion({
// model: "gpt-3.5-turbo",
model: "gpt-4",
messages: messages.map(x => {
return {
"role": x.role,
"content": x.content
}
})
});
console.log("completion: ", completion);
responseMsg = completion.data.choices[0].message.content;
console.log("responseMsg: ", responseMsg);
} catch (e) {
console.log("OpenAI API error: ", e);
if(retry === 0) {
throw new Error("OpenAI API error");
}
return await createChatCompletion(messages, retry - 1);
}
return responseMsg;
};
module.exports = {
createChatCompletion
};