forked from njerschow/openai-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (59 loc) · 1.61 KB
/
index.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
"use strict";
const config = require('./config');
const axios = require('axios');
const DEFAULT_ENGINE = "davinci";
class OpenAI {
constructor(api_key) {
this._api_key = api_key;
}
_send_request(url, method, opts = {}) {
let camelToUnderscore = (key) => {
let result = key.replace(/([A-Z])/g, " $1");
return result.split(' ').join('_').toLowerCase();
}
const data = {};
for (const key in opts) {
data[camelToUnderscore(key)] = opts[key];
}
return axios({
url,
headers: {
'Authorization': `Bearer ${this._api_key}`,
'Content-Type': 'application/json'
},
data: Object.keys(data).length ? data : '',
method,
});
}
complete(opts) {
const url = config.completionURL(opts.engine || DEFAULT_ENGINE);
delete opts.engine;
return this._send_request(url, 'post', opts);
}
encode() {
// This method is no longer supported in Node>=v14. See
return Promise.resolve(new Array(2047).fill(""));
}
search(opts) {
const url = config.searchURL(opts.engine || DEFAULT_ENGINE)
delete opts.engine;
return this._send_request(url, 'post', opts);
}
answers(opts) {
const url = config.answersUrl();
return this._send_request(url, 'post', opts);
}
classification(opts) {
const url = config.classificationsUrl();
return this._send_request(url, "post", opts);
}
engines() {
const url = config.enginesUrl();
return this._send_request(url, 'get')
}
engine(engine) {
const url = config.engineUrl(engine);
return this._send_request(url, 'get');
}
}
module.exports = OpenAI;