lobe-chat

Форк
0
/
toolManifest.ts 
124 строки · 3.1 Кб
1
import { LobeChatPluginManifest, pluginManifestSchema } from '@lobehub/chat-plugin-sdk';
2

3
import { API_ENDPOINTS } from '@/services/_url';
4
import { OpenAIPluginManifest } from '@/types/openai/plugin';
5

6
const fetchJSON = async <T = any>(url: string, proxy = false): Promise<T> => {
7
  // 2. 发送请求
8
  let res: Response;
9
  try {
10
    res = await (proxy ? fetch(API_ENDPOINTS.proxy, { body: url, method: 'POST' }) : fetch(url));
11
  } catch {
12
    throw new TypeError('fetchError');
13
  }
14

15
  if (!res.ok) {
16
    throw new TypeError('fetchError');
17
  }
18

19
  let data;
20
  const contentType = res.headers.get('Content-Type');
21

22
  try {
23
    if (contentType === 'application/json') {
24
      data = await res.json();
25
    } else {
26
      const { default: YAML } = await import('yaml');
27

28
      const yaml = await res.text();
29
      data = YAML.parse(yaml);
30
    }
31
  } catch {
32
    throw new TypeError('urlError');
33
  }
34

35
  return data;
36
};
37

38
export const convertOpenAIManifestToLobeManifest = (
39
  data: OpenAIPluginManifest,
40
): LobeChatPluginManifest => {
41
  const manifest: LobeChatPluginManifest = {
42
    api: [],
43
    homepage: data.legal_info_url,
44
    identifier: data.name_for_model,
45
    meta: {
46
      avatar: data.logo_url,
47
      description: data.description_for_human,
48
      title: data.name_for_human,
49
    },
50
    openapi: data.api.url,
51
    systemRole: data.description_for_model,
52
    type: 'default',
53
    version: '1',
54
  };
55
  switch (data.auth.type) {
56
    case 'none': {
57
      break;
58
    }
59
    case 'service_http': {
60
      manifest.settings = {
61
        properties: {
62
          apiAuthKey: {
63
            default: data.auth.verification_tokens['openai'],
64
            description: 'API Key',
65
            format: 'password',
66
            title: 'API Key',
67
            type: 'string',
68
          },
69
        },
70
        type: 'object',
71
      };
72
      break;
73
    }
74
  }
75

76
  return manifest;
77
};
78

79
export const getToolManifest = async (
80
  url?: string,
81
  useProxy: boolean = false,
82
): Promise<LobeChatPluginManifest> => {
83
  // 1. valid plugin
84
  if (!url) {
85
    throw new TypeError('noManifest');
86
  }
87

88
  // 2. 发送请求
89

90
  let data = await fetchJSON<LobeChatPluginManifest>(url, useProxy);
91

92
  // @ts-ignore
93
  // if there is a description_for_model, it is an OpenAI plugin
94
  // we need convert to lobe plugin
95
  if (data['description_for_model']) {
96
    data = convertOpenAIManifestToLobeManifest(data as any);
97
  }
98

99
  // 3. 校验插件文件格式规范
100
  const parser = pluginManifestSchema.safeParse(data);
101

102
  if (!parser.success) {
103
    throw new TypeError('manifestInvalid', { cause: parser.error });
104
  }
105

106
  // 4. if exist OpenAPI api, merge the OpenAPIs to api
107
  if (parser.data.openapi) {
108
    const openapiJson = await fetchJSON(parser.data.openapi, useProxy);
109

110
    try {
111
      const { OpenAPIConvertor } = await import('@lobehub/chat-plugin-sdk/openapi');
112

113
      const convertor = new OpenAPIConvertor(openapiJson);
114
      const openAPIs = await convertor.convertOpenAPIToPluginSchema();
115
      data.api = [...data.api, ...openAPIs];
116

117
      data.settings = await convertor.convertAuthToSettingsSchema(data.settings);
118
    } catch (error) {
119
      throw new TypeError('openAPIInvalid', { cause: error });
120
    }
121
  }
122

123
  return data;
124
};
125

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.