File size: 1,764 Bytes
9705b6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
require('dotenv').config();
const { KeyvFile } = require('keyv-file');
const { getUserKey, checkUserKeyExpiry } = require('../server/services/UserService');

const browserClient = async ({
  text,
  parentMessageId,
  conversationId,
  model,
  key: expiresAt,
  onProgress,
  onEventMessage,
  abortController,
  userId,
}) => {
  const isUserProvided = process.env.CHATGPT_TOKEN === 'user_provided';

  let key = null;
  if (expiresAt && isUserProvided) {
    checkUserKeyExpiry(
      expiresAt,
      'Your ChatGPT Access Token has expired. Please provide your token again.',
    );
    key = await getUserKey({ userId, name: 'chatGPTBrowser' });
  }

  const { ChatGPTBrowserClient } = await import('@waylaidwanderer/chatgpt-api');
  const store = {
    store: new KeyvFile({ filename: './data/cache.json' }),
  };

  const clientOptions = {
    // Warning: This will expose your access token to a third party. Consider the risks before using this.
    reverseProxyUrl:
      process.env.CHATGPT_REVERSE_PROXY ?? 'https://ai.fakeopen.com/api/conversation',
    // Access token from https://chat.openai.com/api/auth/session
    accessToken: isUserProvided ? key : process.env.CHATGPT_TOKEN ?? null,
    model: model,
    debug: false,
    proxy: process.env.PROXY ?? null,
    user: userId,
  };

  const client = new ChatGPTBrowserClient(clientOptions, store);
  let options = { onProgress, onEventMessage, abortController };

  if (!!parentMessageId && !!conversationId) {
    options = { ...options, parentMessageId, conversationId };
  }

  if (parentMessageId === '00000000-0000-0000-0000-000000000000') {
    delete options.conversationId;
  }

  const res = await client.sendMessage(text, options);
  return res;
};

module.exports = { browserClient };