File size: 8,973 Bytes
3b6afc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const express = require('express');
const crypto = require('crypto');
const router = express.Router();
const { titleConvoBing, askBing } = require('../../../app');
const { saveMessage, getConvoTitle, saveConvo, getConvo } = require('../../../models');
const { handleError, sendMessage, createOnProgress, handleText } = require('./handlers');
const requireJwtAuth = require('../../../middleware/requireJwtAuth');

router.post('/', requireJwtAuth, async (req, res) => {
  const {
    endpoint,
    text,
    messageId,
    overrideParentMessageId = null,
    parentMessageId,
    conversationId: oldConversationId,
  } = req.body;
  if (text.length === 0) {
    return handleError(res, { text: 'Prompt empty or too short' });
  }
  if (endpoint !== 'bingAI') {
    return handleError(res, { text: 'Illegal request' });
  }

  // build user message
  const conversationId = oldConversationId || crypto.randomUUID();
  const isNewConversation = !oldConversationId;
  const userMessageId = messageId;
  const userParentMessageId = parentMessageId || '00000000-0000-0000-0000-000000000000';
  let userMessage = {
    messageId: userMessageId,
    sender: 'User',
    text,
    parentMessageId: userParentMessageId,
    conversationId,
    isCreatedByUser: true,
  };

  // build endpoint option
  let endpointOption = {};
  if (req.body?.jailbreak) {
    endpointOption = {
      jailbreak: req.body?.jailbreak ?? false,
      jailbreakConversationId: req.body?.jailbreakConversationId ?? null,
      systemMessage: req.body?.systemMessage ?? null,
      context: req.body?.context ?? null,
      toneStyle: req.body?.toneStyle ?? 'creative',
      token: req.body?.token ?? null,
    };
  } else {
    endpointOption = {
      jailbreak: req.body?.jailbreak ?? false,
      systemMessage: req.body?.systemMessage ?? null,
      context: req.body?.context ?? null,
      conversationSignature: req.body?.conversationSignature ?? null,
      clientId: req.body?.clientId ?? null,
      invocationId: req.body?.invocationId ?? null,
      toneStyle: req.body?.toneStyle ?? 'creative',
      token: req.body?.token ?? null,
    };
  }

  console.log('ask log', {
    userMessage,
    endpointOption,
    conversationId,
  });

  if (!overrideParentMessageId) {
    await saveMessage(userMessage);
    await saveConvo(req.user.id, {
      ...userMessage,
      ...endpointOption,
      conversationId,
      endpoint,
    });
  }

  // eslint-disable-next-line no-use-before-define
  return await ask({
    isNewConversation,
    userMessage,
    endpointOption,
    conversationId,
    preSendRequest: true,
    overrideParentMessageId,
    req,
    res,
  });
});

const ask = async ({
  isNewConversation,
  userMessage,
  endpointOption,
  conversationId,
  preSendRequest = true,
  overrideParentMessageId = null,
  req,
  res,
}) => {
  let { text, parentMessageId: userParentMessageId, messageId: userMessageId } = userMessage;

  let responseMessageId = crypto.randomUUID();

  res.writeHead(200, {
    Connection: 'keep-alive',
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache, no-transform',
    'Access-Control-Allow-Origin': '*',
    'X-Accel-Buffering': 'no',
  });

  if (preSendRequest) {
    sendMessage(res, { message: userMessage, created: true });
  }

  let lastSavedTimestamp = 0;
  const { onProgress: progressCallback, getPartialText } = createOnProgress({
    onProgress: ({ text }) => {
      const currentTimestamp = Date.now();
      if (currentTimestamp - lastSavedTimestamp > 500) {
        lastSavedTimestamp = currentTimestamp;
        saveMessage({
          messageId: responseMessageId,
          sender: endpointOption?.jailbreak ? 'Sydney' : 'BingAI',
          conversationId,
          parentMessageId: overrideParentMessageId || userMessageId,
          text: text,
          unfinished: true,
          cancelled: false,
          error: false,
        });
      }
    },
  });
  const abortController = new AbortController();
  let bingConversationId = null;
  if (!isNewConversation) {
    const convo = await getConvo(req.user.id, conversationId);
    bingConversationId = convo.bingConversationId;
  }

  try {
    let response = await askBing({
      text,
      parentMessageId: userParentMessageId,
      conversationId: bingConversationId ?? conversationId,
      ...endpointOption,
      onProgress: progressCallback.call(null, {
        res,
        text,
        parentMessageId: overrideParentMessageId || userMessageId,
      }),
      abortController,
    });

    console.log('BING RESPONSE', response);

    const newConversationId = endpointOption?.jailbreak
      ? response.jailbreakConversationId
      : response.conversationId || conversationId;
    const newUserMessageId =
      response.parentMessageId || response.details.requestId || userMessageId;
    const newResponseMessageId = response.messageId || response.details.messageId;

    // STEP1 generate response message
    response.text =
      response.response || response.details.spokenText || '**Bing refused to answer.**';

    const partialText = getPartialText();
    let unfinished = false;
    if (partialText?.trim()?.length > response.text.length) {
      response.text = partialText;
      unfinished = false;
      //setting "unfinished" to false fix bing image generation error msg and allows to continue a convo after being triggered by censorship (bing does remember the context after a "censored error" so there is no reason to end the convo)
    }

    let responseMessage = {
      conversationId,
      bingConversationId: newConversationId,
      messageId: responseMessageId,
      newMessageId: newResponseMessageId,
      parentMessageId: overrideParentMessageId || newUserMessageId,
      sender: endpointOption?.jailbreak ? 'Sydney' : 'BingAI',
      text: await handleText(response, true),
      suggestions:
        response.details.suggestedResponses &&
        response.details.suggestedResponses.map((s) => s.text),
      unfinished,
      cancelled: false,
      error: false,
    };

    await saveMessage(responseMessage);
    responseMessage.messageId = newResponseMessageId;

    let conversationUpdate = {
      conversationId,
      bingConversationId: newConversationId,
      endpoint: 'bingAI',
    };

    if (endpointOption?.jailbreak) {
      conversationUpdate.jailbreak = true;
      conversationUpdate.jailbreakConversationId = response.jailbreakConversationId;
    } else {
      conversationUpdate.jailbreak = false;
      conversationUpdate.conversationSignature = response.conversationSignature;
      conversationUpdate.clientId = response.clientId;
      conversationUpdate.invocationId = response.invocationId;
    }

    await saveConvo(req.user.id, conversationUpdate);
    userMessage.messageId = newUserMessageId;

    // If response has parentMessageId, the fake userMessage.messageId should be updated to the real one.
    if (!overrideParentMessageId) {
      await saveMessage({
        ...userMessage,
        messageId: userMessageId,
        newMessageId: newUserMessageId,
      });
    }
    userMessageId = newUserMessageId;

    sendMessage(res, {
      title: await getConvoTitle(req.user.id, conversationId),
      final: true,
      conversation: await getConvo(req.user.id, conversationId),
      requestMessage: userMessage,
      responseMessage: responseMessage,
    });
    res.end();

    if (userParentMessageId == '00000000-0000-0000-0000-000000000000') {
      const title = await titleConvoBing({
        text,
        response: responseMessage,
      });

      await saveConvo(req.user.id, {
        conversationId: conversationId,
        title,
      });
    }
  } catch (error) {
    console.error(error);
    const partialText = getPartialText();
    if (partialText?.length > 2) {
      const responseMessage = {
        messageId: responseMessageId,
        sender: endpointOption?.jailbreak ? 'Sydney' : 'BingAI',
        conversationId,
        parentMessageId: overrideParentMessageId || userMessageId,
        text: partialText,
        model: endpointOption.modelOptions.model,
        unfinished: true,
        cancelled: false,
        error: false,
      };

      saveMessage(responseMessage);

      return {
        title: await getConvoTitle(req.user.id, conversationId),
        final: true,
        conversation: await getConvo(req.user.id, conversationId),
        requestMessage: userMessage,
        responseMessage: responseMessage,
      };
    } else {
      console.log(error);
      const errorMessage = {
        messageId: responseMessageId,
        sender: endpointOption?.jailbreak ? 'Sydney' : 'BingAI',
        conversationId,
        parentMessageId: overrideParentMessageId || userMessageId,
        unfinished: false,
        cancelled: false,
        error: true,
        text: error.message,
      };
      await saveMessage(errorMessage);
      handleError(res, errorMessage);
    }
  }
};

module.exports = router;