File size: 1,886 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
61
62
63
64
const { PluginsClient } = require('../../../../app');
const { isEnabled } = require('../../../utils');
const { getAzureCredentials } = require('../../../../utils');
const { getUserKey, checkUserKeyExpiry } = require('../../../services/UserService');

const initializeClient = async ({ req, res, endpointOption }) => {
  const {
    PROXY,
    OPENAI_API_KEY,
    AZURE_API_KEY,
    PLUGINS_USE_AZURE,
    OPENAI_REVERSE_PROXY,
    OPENAI_SUMMARIZE,
    DEBUG_PLUGINS,
  } = process.env;
  const { key: expiresAt } = req.body;
  const contextStrategy = isEnabled(OPENAI_SUMMARIZE) ? 'summarize' : null;
  const clientOptions = {
    contextStrategy,
    debug: isEnabled(DEBUG_PLUGINS),
    reverseProxyUrl: OPENAI_REVERSE_PROXY ?? null,
    proxy: PROXY ?? null,
    req,
    res,
    ...endpointOption,
  };

  const isUserProvided = PLUGINS_USE_AZURE
    ? AZURE_API_KEY === 'user_provided'
    : OPENAI_API_KEY === 'user_provided';

  let key = null;
  if (expiresAt && isUserProvided) {
    checkUserKeyExpiry(
      expiresAt,
      'Your OpenAI API key has expired. Please provide your API key again.',
    );
    key = await getUserKey({
      userId: req.user.id,
      name: PLUGINS_USE_AZURE ? 'azureOpenAI' : 'openAI',
    });
  }

  let openAIApiKey = isUserProvided ? key : OPENAI_API_KEY;

  if (PLUGINS_USE_AZURE) {
    clientOptions.azure = isUserProvided ? JSON.parse(key) : getAzureCredentials();
    openAIApiKey = clientOptions.azure.azureOpenAIApiKey;
  }

  if (openAIApiKey && openAIApiKey.includes('azure') && !clientOptions.azure) {
    clientOptions.azure = isUserProvided ? JSON.parse(key) : getAzureCredentials();
    openAIApiKey = clientOptions.azure.azureOpenAIApiKey;
  }
  const client = new PluginsClient(openAIApiKey, clientOptions);
  return {
    client,
    azure: clientOptions.azure,
    openAIApiKey,
  };
};

module.exports = initializeClient;