-
Notifications
You must be signed in to change notification settings - Fork 718
/
chatgpt-web.mjs
303 lines (285 loc) · 9.9 KB
/
chatgpt-web.mjs
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// web version
import { fetchSSE } from '../../utils/fetch-sse.mjs'
import { isEmpty } from 'lodash-es'
import { chatgptWebModelKeys, getUserConfig, Models } from '../../config/index.mjs'
import { pushRecord, setAbortController } from './shared.mjs'
import Browser from 'webextension-polyfill'
import { v4 as uuidv4 } from 'uuid'
import { t } from 'i18next'
async function request(token, method, path, data) {
const apiUrl = (await getUserConfig()).customChatGptWebApiUrl
const response = await fetch(`${apiUrl}/backend-api${path}`, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
})
const responseText = await response.text()
console.debug(`request: ${path}`, responseText)
return { response, responseText }
}
export async function sendMessageFeedback(token, data) {
await request(token, 'POST', '/conversation/message_feedback', data)
}
export async function setConversationProperty(token, conversationId, propertyObject) {
await request(token, 'PATCH', `/conversation/${conversationId}`, propertyObject)
}
export async function deleteConversation(token, conversationId) {
if (conversationId) await setConversationProperty(token, conversationId, { is_visible: false })
}
export async function sendModerations(token, question, conversationId, messageId) {
await request(token, 'POST', `/moderations`, {
conversation_id: conversationId,
input: question,
message_id: messageId,
model: 'text-moderation-playground',
})
}
export async function getModels(token) {
const response = JSON.parse((await request(token, 'GET', '/models')).responseText)
if (response.models) return response.models.map((m) => m.slug)
}
/**
* @param {Runtime.Port} port
* @param {string} question
* @param {Session} session
* @param {string} accessToken
*/
export async function generateAnswersWithChatgptWebApi(port, question, session, accessToken) {
session.messageId = uuidv4()
if (session.parentMessageId == null) {
session.parentMessageId = uuidv4()
}
let ws
const { controller, cleanController } = setAbortController(
port,
() => {
if (ws) ws.close()
},
() => {
if (session.autoClean) deleteConversation(accessToken, session.conversationId)
if (ws) ws.close()
},
)
const models = await getModels(accessToken).catch(cleanController)
console.debug('models', models)
const config = await getUserConfig()
const selectedModel = Models[session.modelName].value
const usedModel =
models && models.includes(selectedModel) ? selectedModel : Models[chatgptWebModelKeys[0]].value
console.debug('usedModel', usedModel)
let cookie
if (Browser.cookies && Browser.cookies.getAll)
cookie = (await Browser.cookies.getAll({ url: 'https://chat.openai.com/' }))
.map((cookie) => {
return `${cookie.name}=${cookie.value}`
})
.join('; ')
const needArkoseToken = !usedModel.includes(Models[chatgptWebModelKeys[0]].value)
if (needArkoseToken && !config.chatgptArkoseReqUrl)
throw new Error(
t('Please login at https://chat.openai.com first') +
'\n\n' +
t(
"Please keep https://chat.openai.com open and try again. If it still doesn't work, type some characters in the input box of chatgpt web page and try again.",
),
)
const arkoseToken = config.chatgptArkoseReqUrl
? await fetch(config.chatgptArkoseReqUrl + '?' + config.chatgptArkoseReqParams, {
method: 'POST',
body: config.chatgptArkoseReqForm,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
})
.then((resp) => resp.json())
.then((resp) => resp.token)
.catch(() => null)
: null
if (needArkoseToken && !arkoseToken)
throw new Error(
t('Failed to get arkose token.') +
'\n\n' +
t(
"Please keep https://chat.openai.com open and try again. If it still doesn't work, type some characters in the input box of chatgpt web page and try again.",
),
)
let answer = ''
let generationPrefixAnswer = ''
let generatedImageUrl = ''
let wss_url = ''
const url = `${config.customChatGptWebApiUrl}${config.customChatGptWebApiPath}`
const options = {
method: 'POST',
signal: controller.signal,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
...(cookie && { Cookie: cookie }),
},
body: JSON.stringify({
action: 'next',
conversation_id: session.conversationId || undefined,
messages: [
{
id: session.messageId,
author: {
role: 'user',
},
content: {
content_type: 'text',
parts: [question],
},
},
],
conversation_mode: {
kind: 'primary_assistant',
},
force_paragen: false,
force_rate_limit: false,
suggestions: [],
model: usedModel,
parent_message_id: session.parentMessageId,
timezone_offset_min: new Date().getTimezoneOffset(),
history_and_training_disabled: config.disableWebModeHistory,
arkose_token: arkoseToken,
}),
}
await fetchSSE(url, {
...options,
onMessage(message) {
function handleMessage(data) {
if (data.error) {
if (data.error.includes('unusual activity'))
throw new Error(
"Please keep https://chat.openai.com open and try again. If it still doesn't work, type some characters in the input box of chatgpt web page and try again.",
)
else throw new Error(data.error)
}
if (data.conversation_id) session.conversationId = data.conversation_id
if (data.message?.id) session.parentMessageId = data.message.id
const respAns = data.message?.content?.parts?.[0]
const contentType = data.message?.content?.content_type
if (contentType === 'text' && respAns) {
answer =
generationPrefixAnswer +
(generatedImageUrl && `\n\n![](${generatedImageUrl})\n\n`) +
respAns
} else if (contentType === 'code' && data.message?.status === 'in_progress') {
const generationText = '\n\n' + t('Generating...')
if (answer && !answer.endsWith(generationText)) generationPrefixAnswer = answer
answer = generationPrefixAnswer + generationText
} else if (
contentType === 'multimodal_text' &&
respAns?.content_type === 'image_asset_pointer'
) {
const imageAsset = respAns?.asset_pointer || ''
if (imageAsset) {
fetch(
`${config.customChatGptWebApiUrl}/backend-api/files/${imageAsset.replace(
'file-service://',
'',
)}/download`,
{
credentials: 'include',
headers: {
Authorization: `Bearer ${accessToken}`,
...(cookie && { Cookie: cookie }),
},
},
).then((r) => r.json().then((json) => (generatedImageUrl = json?.download_url)))
}
}
if (answer) {
port.postMessage({ answer: answer, done: false, session: null })
}
}
function finishMessage() {
pushRecord(session, question, answer)
console.debug('conversation history', { content: session.conversationRecords })
port.postMessage({ answer: answer, done: true, session: session })
}
console.debug('sse message', message)
if (message.trim() === '[DONE]') {
if (!wss_url) {
finishMessage()
} else {
ws = new WebSocket(wss_url)
ws.onmessage = (event) => {
let wsData
try {
wsData = JSON.parse(event.data)
} catch (error) {
console.debug('json error', error)
return
}
if (wsData.type === 'http.response.body') {
let body
try {
body = atob(wsData.body).replace(/^data:/, '')
const data = JSON.parse(body)
console.debug('ws message', data)
if (wsData.conversation_id === session.conversationId) {
handleMessage(data)
}
} catch (error) {
if (body && body.trim() === '[DONE]') {
console.debug('ws message', '[DONE]')
if (wsData.conversation_id === session.conversationId) {
finishMessage()
ws.close()
}
} else {
console.debug('json error', error)
}
}
}
}
ws.onopen = () => {
// fetch(url, options)
}
ws.onclose = () => {
port.postMessage({ done: true })
cleanController()
}
ws.onerror = (event) => {
console.debug('ws error', event)
port.postMessage({ error: event })
cleanController()
}
}
return
}
let data
try {
data = JSON.parse(message)
} catch (error) {
console.debug('json error', error)
return
}
if (data.wss_url) wss_url = data.wss_url
handleMessage(data)
},
async onStart() {
// sendModerations(accessToken, question, session.conversationId, session.messageId)
},
async onEnd() {
if (!wss_url) {
port.postMessage({ done: true })
cleanController()
}
},
async onError(resp) {
cleanController()
if (resp instanceof Error) throw resp
if (resp.status === 403) {
throw new Error('CLOUDFLARE')
}
const error = await resp.json().catch(() => ({}))
throw new Error(!isEmpty(error) ? JSON.stringify(error) : `${resp.status} ${resp.statusText}`)
},
})
}