EditChannel.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import React, { useEffect, useState } from 'react';
  2. import { Button, Form, Header, Input, Message, Segment } from 'semantic-ui-react';
  3. import { useParams, useNavigate } from 'react-router-dom';
  4. import { API, showError, showInfo, showSuccess, verifyJSON } from '../../helpers';
  5. import { CHANNEL_OPTIONS } from '../../constants';
  6. const MODEL_MAPPING_EXAMPLE = {
  7. 'gpt-3.5-turbo-0301': 'gpt-3.5-turbo',
  8. 'gpt-4-0314': 'gpt-4',
  9. 'gpt-4-32k-0314': 'gpt-4-32k'
  10. };
  11. const EditChannel = () => {
  12. const params = useParams();
  13. const navigate = useNavigate();
  14. const channelId = params.id;
  15. const isEdit = channelId !== undefined;
  16. const [loading, setLoading] = useState(isEdit);
  17. const handleCancel = () => {
  18. navigate('/channel');
  19. };
  20. const originInputs = {
  21. name: '',
  22. type: 1,
  23. key: '',
  24. base_url: '',
  25. other: '',
  26. model_mapping: '',
  27. models: [],
  28. groups: ['default']
  29. };
  30. const [batch, setBatch] = useState(false);
  31. const [inputs, setInputs] = useState(originInputs);
  32. const [originModelOptions, setOriginModelOptions] = useState([]);
  33. const [modelOptions, setModelOptions] = useState([]);
  34. const [groupOptions, setGroupOptions] = useState([]);
  35. const [basicModels, setBasicModels] = useState([]);
  36. const [fullModels, setFullModels] = useState([]);
  37. const [customModel, setCustomModel] = useState('');
  38. const handleInputChange = (e, { name, value }) => {
  39. setInputs((inputs) => ({ ...inputs, [name]: value }));
  40. if (name === 'type' && inputs.models.length === 0) {
  41. let localModels = [];
  42. switch (value) {
  43. case 14:
  44. localModels = ['claude-instant-1', 'claude-2'];
  45. break;
  46. case 11:
  47. localModels = ['PaLM-2'];
  48. break;
  49. case 15:
  50. localModels = ['ERNIE-Bot', 'ERNIE-Bot-turbo', 'Embedding-V1'];
  51. break;
  52. case 17:
  53. localModels = ['qwen-v1', 'qwen-plus-v1'];
  54. break;
  55. case 16:
  56. localModels = ['chatglm_pro', 'chatglm_std', 'chatglm_lite'];
  57. break;
  58. case 18:
  59. localModels = ['SparkDesk'];
  60. break;
  61. }
  62. setInputs((inputs) => ({ ...inputs, models: localModels }));
  63. }
  64. };
  65. const loadChannel = async () => {
  66. let res = await API.get(`/api/channel/${channelId}`);
  67. const { success, message, data } = res.data;
  68. if (success) {
  69. if (data.models === '') {
  70. data.models = [];
  71. } else {
  72. data.models = data.models.split(',');
  73. }
  74. if (data.group === '') {
  75. data.groups = [];
  76. } else {
  77. data.groups = data.group.split(',');
  78. }
  79. if (data.model_mapping !== '') {
  80. data.model_mapping = JSON.stringify(JSON.parse(data.model_mapping), null, 2);
  81. }
  82. setInputs(data);
  83. } else {
  84. showError(message);
  85. }
  86. setLoading(false);
  87. };
  88. const fetchModels = async () => {
  89. try {
  90. let res = await API.get(`/api/channel/models`);
  91. let localModelOptions = res.data.data.map((model) => ({
  92. key: model.id,
  93. text: model.id,
  94. value: model.id
  95. }));
  96. setOriginModelOptions(localModelOptions);
  97. setFullModels(res.data.data.map((model) => model.id));
  98. setBasicModels(res.data.data.filter((model) => {
  99. return model.id.startsWith('gpt-3') || model.id.startsWith('text-');
  100. }).map((model) => model.id));
  101. } catch (error) {
  102. showError(error.message);
  103. }
  104. };
  105. const fetchGroups = async () => {
  106. try {
  107. let res = await API.get(`/api/group/`);
  108. setGroupOptions(res.data.data.map((group) => ({
  109. key: group,
  110. text: group,
  111. value: group
  112. })));
  113. } catch (error) {
  114. showError(error.message);
  115. }
  116. };
  117. useEffect(() => {
  118. let localModelOptions = [...originModelOptions];
  119. inputs.models.forEach((model) => {
  120. if (!localModelOptions.find((option) => option.key === model)) {
  121. localModelOptions.push({
  122. key: model,
  123. text: model,
  124. value: model
  125. });
  126. }
  127. });
  128. setModelOptions(localModelOptions);
  129. }, [originModelOptions, inputs.models]);
  130. useEffect(() => {
  131. if (isEdit) {
  132. loadChannel().then();
  133. }
  134. fetchModels().then();
  135. fetchGroups().then();
  136. }, []);
  137. const submit = async () => {
  138. if (!isEdit && (inputs.name === '' || inputs.key === '')) {
  139. showInfo('请填写渠道名称和渠道密钥!');
  140. return;
  141. }
  142. if (inputs.models.length === 0) {
  143. showInfo('请至少选择一个模型!');
  144. return;
  145. }
  146. if (inputs.model_mapping !== '' && !verifyJSON(inputs.model_mapping)) {
  147. showInfo('模型映射必须是合法的 JSON 格式!');
  148. return;
  149. }
  150. let localInputs = inputs;
  151. if (localInputs.base_url.endsWith('/')) {
  152. localInputs.base_url = localInputs.base_url.slice(0, localInputs.base_url.length - 1);
  153. }
  154. if (localInputs.type === 3 && localInputs.other === '') {
  155. localInputs.other = '2023-06-01-preview';
  156. }
  157. if (localInputs.model_mapping === '') {
  158. localInputs.model_mapping = '{}';
  159. }
  160. let res;
  161. localInputs.models = localInputs.models.join(',');
  162. localInputs.group = localInputs.groups.join(',');
  163. if (isEdit) {
  164. res = await API.put(`/api/channel/`, { ...localInputs, id: parseInt(channelId) });
  165. } else {
  166. res = await API.post(`/api/channel/`, localInputs);
  167. }
  168. const { success, message } = res.data;
  169. if (success) {
  170. if (isEdit) {
  171. showSuccess('渠道更新成功!');
  172. } else {
  173. showSuccess('渠道创建成功!');
  174. setInputs(originInputs);
  175. }
  176. } else {
  177. showError(message);
  178. }
  179. };
  180. return (
  181. <>
  182. <Segment loading={loading}>
  183. <Header as='h3'>{isEdit ? '更新渠道信息' : '创建新的渠道'}</Header>
  184. <Form autoComplete='new-password'>
  185. <Form.Field>
  186. <Form.Select
  187. label='类型'
  188. name='type'
  189. required
  190. options={CHANNEL_OPTIONS}
  191. value={inputs.type}
  192. onChange={handleInputChange}
  193. />
  194. </Form.Field>
  195. {
  196. inputs.type === 3 && (
  197. <>
  198. <Message>
  199. 注意,<strong>模型部署名称必须和模型名称保持一致</strong>,因为 One API 会把请求体中的 model
  200. 参数替换为你的部署名称(模型名称中的点会被剔除),<a target='_blank'
  201. href='https://github.com/songquanpeng/one-api/issues/133?notification_referrer_id=NT_kwDOAmJSYrM2NjIwMzI3NDgyOjM5OTk4MDUw#issuecomment-1571602271'>图片演示</a>。
  202. </Message>
  203. <Form.Field>
  204. <Form.Input
  205. label='AZURE_OPENAI_ENDPOINT'
  206. name='base_url'
  207. placeholder={'请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com'}
  208. onChange={handleInputChange}
  209. value={inputs.base_url}
  210. autoComplete='new-password'
  211. />
  212. </Form.Field>
  213. <Form.Field>
  214. <Form.Input
  215. label='默认 API 版本'
  216. name='other'
  217. placeholder={'请输入默认 API 版本,例如:2023-06-01-preview,该配置可以被实际的请求查询参数所覆盖'}
  218. onChange={handleInputChange}
  219. value={inputs.other}
  220. autoComplete='new-password'
  221. />
  222. </Form.Field>
  223. </>
  224. )
  225. }
  226. {
  227. inputs.type === 8 && (
  228. <Form.Field>
  229. <Form.Input
  230. label='Base URL'
  231. name='base_url'
  232. placeholder={'请输入自定义渠道的 Base URL,例如:https://openai.justsong.cn'}
  233. onChange={handleInputChange}
  234. value={inputs.base_url}
  235. autoComplete='new-password'
  236. />
  237. </Form.Field>
  238. )
  239. }
  240. <Form.Field>
  241. <Form.Input
  242. label='名称'
  243. required
  244. name='name'
  245. placeholder={'请为渠道命名'}
  246. onChange={handleInputChange}
  247. value={inputs.name}
  248. autoComplete='new-password'
  249. />
  250. </Form.Field>
  251. <Form.Field>
  252. <Form.Dropdown
  253. label='分组'
  254. placeholder={'请选择可以使用该渠道的分组'}
  255. name='groups'
  256. required
  257. fluid
  258. multiple
  259. selection
  260. allowAdditions
  261. additionLabel={'请在系统设置页面编辑分组倍率以添加新的分组:'}
  262. onChange={handleInputChange}
  263. value={inputs.groups}
  264. autoComplete='new-password'
  265. options={groupOptions}
  266. />
  267. </Form.Field>
  268. <Form.Field>
  269. <Form.Dropdown
  270. label='模型'
  271. placeholder={'请选择该渠道所支持的模型'}
  272. name='models'
  273. required
  274. fluid
  275. multiple
  276. selection
  277. onChange={handleInputChange}
  278. value={inputs.models}
  279. autoComplete='new-password'
  280. options={modelOptions}
  281. />
  282. </Form.Field>
  283. <div style={{ lineHeight: '40px', marginBottom: '12px' }}>
  284. <Button type={'button'} onClick={() => {
  285. handleInputChange(null, { name: 'models', value: basicModels });
  286. }}>填入基础模型</Button>
  287. <Button type={'button'} onClick={() => {
  288. handleInputChange(null, { name: 'models', value: fullModels });
  289. }}>填入所有模型</Button>
  290. <Button type={'button'} onClick={() => {
  291. handleInputChange(null, { name: 'models', value: [] });
  292. }}>清除所有模型</Button>
  293. <Input
  294. action={
  295. <Button type={'button'} onClick={() => {
  296. if (customModel.trim() === '') return;
  297. if (inputs.models.includes(customModel)) return;
  298. let localModels = [...inputs.models];
  299. localModels.push(customModel);
  300. let localModelOptions = [];
  301. localModelOptions.push({
  302. key: customModel,
  303. text: customModel,
  304. value: customModel
  305. });
  306. setModelOptions(modelOptions => {
  307. return [...modelOptions, ...localModelOptions];
  308. });
  309. setCustomModel('');
  310. handleInputChange(null, { name: 'models', value: localModels });
  311. }}>填入</Button>
  312. }
  313. placeholder='输入自定义模型名称'
  314. value={customModel}
  315. onChange={(e, { value }) => {
  316. setCustomModel(value);
  317. }}
  318. />
  319. </div>
  320. <Form.Field>
  321. <Form.TextArea
  322. label='模型重定向'
  323. placeholder={`此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`}
  324. name='model_mapping'
  325. onChange={handleInputChange}
  326. value={inputs.model_mapping}
  327. style={{ minHeight: 150, fontFamily: 'JetBrains Mono, Consolas' }}
  328. autoComplete='new-password'
  329. />
  330. </Form.Field>
  331. {
  332. batch ? <Form.Field>
  333. <Form.TextArea
  334. label='密钥'
  335. name='key'
  336. required
  337. placeholder={'请输入密钥,一行一个'}
  338. onChange={handleInputChange}
  339. value={inputs.key}
  340. style={{ minHeight: 150, fontFamily: 'JetBrains Mono, Consolas' }}
  341. autoComplete='new-password'
  342. />
  343. </Form.Field> : <Form.Field>
  344. <Form.Input
  345. label='密钥'
  346. name='key'
  347. required
  348. placeholder={inputs.type === 15 ? '请输入 access token,当前版本暂不支持自动刷新,请每 30 天更新一次' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥')}
  349. onChange={handleInputChange}
  350. value={inputs.key}
  351. autoComplete='new-password'
  352. />
  353. </Form.Field>
  354. }
  355. {
  356. !isEdit && (
  357. <Form.Checkbox
  358. checked={batch}
  359. label='批量创建'
  360. name='batch'
  361. onChange={() => setBatch(!batch)}
  362. />
  363. )
  364. }
  365. {
  366. inputs.type !== 3 && inputs.type !== 8 && (
  367. <Form.Field>
  368. <Form.Input
  369. label='代理'
  370. name='base_url'
  371. placeholder={'此项可选,用于通过代理站来进行 API 调用,请输入代理站地址,格式为:https://domain.com'}
  372. onChange={handleInputChange}
  373. value={inputs.base_url}
  374. autoComplete='new-password'
  375. />
  376. </Form.Field>
  377. )
  378. }
  379. <Button onClick={handleCancel}>取消</Button>
  380. <Button type={isEdit ? 'button' : 'submit'} positive onClick={submit}>提交</Button>
  381. </Form>
  382. </Segment>
  383. </>
  384. );
  385. };
  386. export default EditChannel;