This repository has been archived by the owner on Apr 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openai.js
196 lines (154 loc) · 4.34 KB
/
openai.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
const { SocksProxyAgent } = require('socks-proxy-agent');
const readline = require('readline');
const {log, cache} = require('./debug.js');
const {sleep} = require('./cli.js');
const config = require('./config.json');
const crypto = require('crypto');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const MODEL = 'gpt-3.5-turbo';
const clearLoading = () => {
process.stdout.clearLine();
process.stdout.cursorTo(0);
};
let agent = null;
if(config.SOCKS_PROXY_HOST && config.SOCKS_PROXY_PORT) {
agent = new SocksProxyAgent(`socks://${config.SOCKS_PROXY_HOST}:${config.SOCKS_PROXY_PORT}`);
}
async function ask(prompt, parentMessageId = null, conversationId = null, preserveHistory = false) {
let hash;
if(config.APP_DEBUG) {
hash = crypto.createHash('md5').update(prompt).digest('hex');
let result = cache(hash);
if(result) {
return result;
}
log(hash);
}
let params = {
model: MODEL,
stream: true,
messages: [
{
role: "user",
content: prompt
}
],
};
let response = await sendChat(params);
let msg = response.choices[0].message || response.choices[0].delta;
log(`prompt:\n${prompt}\n\ncontent:\n${msg.content}\n`)
let result = {
content: msg.content
};
if(config.APP_DEBUG) {
cache(hash, result);
}
return result;
}
async function sendChat(params) {
const url = `${config.OPENAI_API_HOST || 'https://api.openai.com/v1'}/chat/completions`;
// console.log(url, params);
const options = {
method: 'POST',
headers: {
'accept': 'text/event-stream',
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.OPENAI_API_KEY}`,
},
body: JSON.stringify(params),
timeout: 100000,
agent: agent
};
let resp;
try {
resp = await fetchSSE(url, options);
} catch(e) {
await sleep(5000);
resp = await sendChat(params);
}
return resp;
}
async function fetchSSE(url, options) {
return fetch(url, options)
.then(async res => {
const result = await readResultFromStream(res.body);
return result;
})
.catch(error => {
clearLoading();
console.error("Error sending POST request to ChatGPT API:", error);
throw error;
});
}
function readResultFromStream(body) {
return new Promise((resolve, reject) => {
const chunks = [];
let isDone = false;
let i = 0;
let loading = false;
let dot_count = 0;
let resp;
body.on('readable', () => {
timeout = false;
let chunk;
if(isDone) {
return;
}
while (null !== (chunk = body.read())) {
resp = chunk.toString();
if(resp.includes('rate_limit_exceeded')) {
reject('rate limit exceeded');
}
if(!loading) {
process.stdout.write('loading');
loading = true;
}
process.stdout.write('.');
dot_count++;
if (dot_count % 10 == 0) {
process.stdout.write("\b".repeat(dot_count));
readline.clearScreenDown(process.stdout);
dot_count = 0;
}
let arr = resp.split("\n\n").filter(text => text);
arr.forEach(part=>{
if(part.startsWith('data: ')) {
chunks.push(part);
} else {
chunks[chunks.length - 1] += part;
}
if(typeof chunks[0] == 'string' && chunks[0].startsWith('data: ') && chunks[0].endsWith('}')) {
chunks[0] = JSON.parse(chunks[0].replace('data: ', ''));
}
if(chunks.length > 1 && chunks[1].startsWith('data: ') && chunks[1].endsWith('}')) {
chunks[1] = JSON.parse(chunks[1].replace('data: ', ''));
chunks[0].choices[0].delta.content += chunks[1].choices[0].delta.content || '';
chunks.splice(1, 1);
}
});
if(chunks.includes('data: [DONE]')) {
isDone = true;
}
if(isDone) {
clearLoading();
if(!chunks[0]) {
reject(resp || 'empty response');
}
resolve(chunks[0]);
}
}
});
body.on('end', () => {
if(!chunks[0]) {
reject(resp || 'empty response');
}
resolve(chunks[0]);
})
body.on('error', (err) => {
reject(err);
});
});
}
module.exports = {
ask
};