-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
249 lines (222 loc) · 6.35 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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
const axios = require("axios");
const https = require("https");
const { randomUUID } = require("crypto");
const baseUrl = "https://chat.openai.com";
const apiUrl = `${baseUrl}/backend-api/conversation`;
let token;
let oaiDeviceId;
async function getNewSessionId() {
let newDeviceId = randomUUID();
const response = await axiosInstance.post(
`${baseUrl}/backend-anon/sentinel/chat-requirements`,
{},
{
headers: { "oai-device-id": newDeviceId },
}
);
// console.log(
// `System: Successfully refreshed session ID and token. ${
// !token ? "(Now it's ready to process requests)" : ""
// }`
// );
oaiDeviceId = newDeviceId;
token = response.data.token;
// console.log("New Token:", token);
// console.log("New Device ID:", oaiDeviceId);
}
function GenerateCompletionId(prefix = "cmpl-") {
const characters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const length = 28;
for (let i = 0; i < length; i++) {
prefix += characters.charAt(Math.floor(Math.random() * characters.length));
}
return prefix;
}
async function* chunksToLines(chunksAsync) {
let previous = "";
for await (const chunk of chunksAsync) {
const bufferChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
previous += bufferChunk;
let eolIndex;
while ((eolIndex = previous.indexOf("\n")) >= 0) {
// line includes the EOL
const line = previous.slice(0, eolIndex + 1).trimEnd();
if (line === "data: [DONE]") break;
if (line.startsWith("data: ")) yield line;
previous = previous.slice(eolIndex + 1);
}
}
}
async function* linesToMessages(linesAsync) {
for await (const line of linesAsync) {
const message = line.substring("data :".length);
yield message;
}
}
async function* messagesToRes(messagesAsync) {
for await (const message of messagesAsync) {
let requestId = GenerateCompletionId("chatcmpl-");
let created = Date.now();
let response = {
id: requestId,
created: created,
object: "chat.completion.chunk",
model: "gpt-3.5-turbo",
choices: [
{
delta: {
content: JSON.parse(message)?.message?.content?.parts[0] || "",
},
index: 0,
finish_reason: null,
},
],
};
yield response;
}
}
async function* StreamCompletion(data) {
yield* linesToMessages(chunksToLines(data));
}
async function* StreamFinalReturn(data) {
yield* messagesToRes(linesToMessages(chunksToLines(data)));
}
// Setup axios instance for API requests with predefined configurations
const axiosInstance = axios.create({
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
headers: {
accept: "*/*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"content-type": "application/json",
"oai-language": "en-US",
origin: baseUrl,
pragma: "no-cache",
referer: baseUrl,
"sec-ch-ua":
'"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
},
});
// Middleware to handle chat completions
async function handleChatCompletion(data, res) {
try {
await getNewSessionId();
const body = {
action: "next",
messages: data.messages.map((message) => ({
author: { role: message.role },
content: { content_type: "text", parts: [message.content] },
})),
parent_message_id: randomUUID(),
model: "text-davinci-002-render-sha",
timezone_offset_min: -180,
suggestions: [],
history_and_training_disabled: true,
conversation_mode: { kind: "primary_assistant" },
websocket_request_id: randomUUID(),
};
const response = await axiosInstance.post(apiUrl, body, {
responseType: "stream",
headers: {
"oai-device-id": oaiDeviceId,
"openai-sentinel-chat-requirements-token": token,
},
});
if (data.stream) return StreamFinalReturn(response.data);
let fullContent = "";
let requestId = GenerateCompletionId("chatcmpl-");
let created = Date.now();
for await (const message of StreamCompletion(response.data)) {
const parsed = JSON.parse(message);
let content = parsed?.message?.content?.parts[0] || "";
for (let message of data.messages) {
if (message.content === content) {
content = "";
break;
}
}
if (content === "") continue;
if (data.stream) {
let response = {
id: requestId,
created: created,
object: "chat.completion.chunk",
model: "gpt-3.5-turbo",
choices: [
{
delta: {
content: content.replace(fullContent, ""),
},
index: 0,
finish_reason: null,
},
],
};
res.write(`data: ${JSON.stringify(response)}\n\n`);
}
fullContent = content.length > fullContent.length ? content : fullContent;
}
if (data.stream) {
res.write(
`data: ${JSON.stringify({
id: requestId,
created: created,
object: "chat.completion.chunk",
model: "gpt-3.5-turbo",
choices: [
{
delta: {
content: "",
},
index: 0,
finish_reason: "stop",
},
],
})}\n\n`
);
} else {
return {
id: requestId,
created: created,
model: "gpt-3.5-turbo",
object: "chat.completion",
choices: [
{
finish_reason: "stop",
index: 0,
message: {
content: fullContent,
role: "assistant",
},
},
],
usage: {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
},
};
}
res.end();
} catch (error) {
// console.log(error.message);
}
}
module.exports = class FreeGPT35 {
chat = {
completions: {
async create(data) {
return handleChatCompletion(data);
},
},
};
constructor() {}
};