-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathextension.js
82 lines (64 loc) · 2 KB
/
extension.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
71
72
73
74
75
76
77
78
79
80
81
82
const vscode = require('vscode');
function sendApiCall (arg) {
const https = require('https');
const apiKey = vscode.workspace.getConfiguration('connect-to-openai').apiKey;
if (!apiKey) {
vscode.window.showErrorMessage('Please provide a valid API key in the entension configuration.');
return;
}
const configs = vscode.workspace.getConfiguration('connect-to-openai').get('parameters');
const denulledConfigs = {}
Object.entries(configs).forEach((entry) => {
if(entry[1] !== null) {
denulledConfigs[entry[0]] = entry[1];
}
})
const data = JSON.stringify({...denulledConfigs, prompt: arg});
const options = {
hostname: 'api.openai.com',
path: '/v1/completions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
}
};
const req = https.request(options, res => {
let response = '';
res.on('data', d => {
response = d;
});
res.on('end', () => {
const parsedRes = JSON.parse(response);
if (parsedRes.error) {
vscode.window.showErrorMessage(`${parsedRes.error.message} Type:${parsedRes.error.type} Param:${parsedRes.error.param} Code:${parsedRes.error.code}`);
return;
}
const editor = vscode.window.activeTextEditor;
const choices = parsedRes.choices.map(choice => choice.text);
editor.edit((editBuilder) => {
editBuilder.insert(editor.selection.end, '\n' + choices)
})
});
});
req.on('error', error => {
console.error(error);
});
req.write(data);
req.end();
return req;
}
function activate (context) {
let disposable = vscode.commands.registerCommand('connect-to-openai.prompt-openai', function () {
const editor = vscode.window.activeTextEditor;
const selection = editor.selection;
const selectedText = editor.document.getText(selection);
sendApiCall(selectedText);
});
context.subscriptions.push(disposable);
}
function deactivate() {}
module.exports = {
activate,
deactivate
}