EditChannel.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. import React, {useEffect, useRef, useState} from 'react';
  2. import {useNavigate, useParams} from 'react-router-dom';
  3. import {API, isMobile, showError, showInfo, showSuccess, verifyJSON} from '../../helpers';
  4. import {CHANNEL_OPTIONS} from '../../constants';
  5. import Title from "@douyinfe/semi-ui/lib/es/typography/title";
  6. import {SideSheet, Space, Spin, Button, Input, Typography, Select, TextArea, Checkbox, Banner} from "@douyinfe/semi-ui";
  7. const MODEL_MAPPING_EXAMPLE = {
  8. 'gpt-3.5-turbo-0301': 'gpt-3.5-turbo',
  9. 'gpt-4-0314': 'gpt-4',
  10. 'gpt-4-32k-0314': 'gpt-4-32k'
  11. };
  12. function type2secretPrompt(type) {
  13. // inputs.type === 15 ? '按照如下格式输入:APIKey|SecretKey' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥')
  14. switch (type) {
  15. case 15:
  16. return '按照如下格式输入:APIKey|SecretKey';
  17. case 18:
  18. return '按照如下格式输入:APPID|APISecret|APIKey';
  19. case 22:
  20. return '按照如下格式输入:APIKey-AppId,例如:fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041';
  21. case 23:
  22. return '按照如下格式输入:AppId|SecretId|SecretKey';
  23. default:
  24. return '请输入渠道对应的鉴权密钥';
  25. }
  26. }
  27. const EditChannel = (props) => {
  28. const navigate = useNavigate();
  29. const channelId = props.editingChannel.id;
  30. const isEdit = channelId !== undefined;
  31. const [loading, setLoading] = useState(isEdit);
  32. const handleCancel = () => {
  33. props.handleClose()
  34. };
  35. const originInputs = {
  36. name: '',
  37. type: 1,
  38. key: '',
  39. openai_organization: '',
  40. base_url: '',
  41. other: '',
  42. model_mapping: '',
  43. models: [],
  44. auto_ban: 1,
  45. groups: ['default']
  46. };
  47. const [batch, setBatch] = useState(false);
  48. const [autoBan, setAutoBan] = useState(true);
  49. // const [autoBan, setAutoBan] = useState(true);
  50. const [inputs, setInputs] = useState(originInputs);
  51. const [originModelOptions, setOriginModelOptions] = useState([]);
  52. const [modelOptions, setModelOptions] = useState([]);
  53. const [groupOptions, setGroupOptions] = useState([]);
  54. const [basicModels, setBasicModels] = useState([]);
  55. const [fullModels, setFullModels] = useState([]);
  56. const [customModel, setCustomModel] = useState('');
  57. const handleInputChange = (name, value) => {
  58. setInputs((inputs) => ({...inputs, [name]: value}));
  59. if (name === 'type' && inputs.models.length === 0) {
  60. let localModels = [];
  61. switch (value) {
  62. case 14:
  63. localModels = ['claude-instant-1', 'claude-2'];
  64. break;
  65. case 11:
  66. localModels = ['PaLM-2'];
  67. break;
  68. case 15:
  69. localModels = ['ERNIE-Bot', 'ERNIE-Bot-turbo', 'ERNIE-Bot-4', 'Embedding-V1'];
  70. break;
  71. case 17:
  72. localModels = ['qwen-turbo', 'qwen-plus', 'text-embedding-v1'];
  73. break;
  74. case 16:
  75. localModels = ['chatglm_pro', 'chatglm_std', 'chatglm_lite'];
  76. break;
  77. case 18:
  78. localModels = ['SparkDesk'];
  79. break;
  80. case 19:
  81. localModels = ['360GPT_S2_V9', 'embedding-bert-512-v1', 'embedding_s1_v1', 'semantic_similarity_s1_v1'];
  82. break;
  83. case 23:
  84. localModels = ['hunyuan'];
  85. break;
  86. }
  87. setInputs((inputs) => ({...inputs, models: localModels}));
  88. }
  89. //setAutoBan
  90. };
  91. const loadChannel = async () => {
  92. setLoading(true)
  93. let res = await API.get(`/api/channel/${channelId}`);
  94. const {success, message, data} = res.data;
  95. if (success) {
  96. if (data.models === '') {
  97. data.models = [];
  98. } else {
  99. data.models = data.models.split(',');
  100. }
  101. if (data.group === '') {
  102. data.groups = [];
  103. } else {
  104. data.groups = data.group.split(',');
  105. }
  106. if (data.model_mapping !== '') {
  107. data.model_mapping = JSON.stringify(JSON.parse(data.model_mapping), null, 2);
  108. }
  109. setInputs(data);
  110. if (data.auto_ban === 0) {
  111. setAutoBan(false);
  112. } else {
  113. setAutoBan(true);
  114. }
  115. // console.log(data);
  116. } else {
  117. showError(message);
  118. }
  119. setLoading(false);
  120. };
  121. const fetchModels = async () => {
  122. try {
  123. let res = await API.get(`/api/channel/models`);
  124. let localModelOptions = res.data.data.map((model) => ({
  125. label: model.id,
  126. value: model.id
  127. }));
  128. setOriginModelOptions(localModelOptions);
  129. setFullModels(res.data.data.map((model) => model.id));
  130. setBasicModels(res.data.data.filter((model) => {
  131. return model.id.startsWith('gpt-3') || model.id.startsWith('text-');
  132. }).map((model) => model.id));
  133. } catch (error) {
  134. showError(error.message);
  135. }
  136. };
  137. const fetchGroups = async () => {
  138. try {
  139. let res = await API.get(`/api/group/`);
  140. setGroupOptions(res.data.data.map((group) => ({
  141. label: group,
  142. value: group
  143. })));
  144. } catch (error) {
  145. showError(error.message);
  146. }
  147. };
  148. useEffect(() => {
  149. let localModelOptions = [...originModelOptions];
  150. inputs.models.forEach((model) => {
  151. if (!localModelOptions.find((option) => option.key === model)) {
  152. localModelOptions.push({
  153. label: model,
  154. value: model
  155. });
  156. }
  157. });
  158. setModelOptions(localModelOptions);
  159. }, [originModelOptions, inputs.models]);
  160. useEffect(() => {
  161. fetchModels().then();
  162. fetchGroups().then();
  163. if (isEdit) {
  164. loadChannel().then(
  165. () => {
  166. }
  167. );
  168. } else {
  169. setInputs(originInputs)
  170. }
  171. }, [props.editingChannel.id]);
  172. const submit = async () => {
  173. if (!isEdit && (inputs.name === '' || inputs.key === '')) {
  174. showInfo('请填写渠道名称和渠道密钥!');
  175. return;
  176. }
  177. if (inputs.models.length === 0) {
  178. showInfo('请至少选择一个模型!');
  179. return;
  180. }
  181. if (inputs.model_mapping !== '' && !verifyJSON(inputs.model_mapping)) {
  182. showInfo('模型映射必须是合法的 JSON 格式!');
  183. return;
  184. }
  185. let localInputs = {...inputs};
  186. if (localInputs.base_url && localInputs.base_url.endsWith('/')) {
  187. localInputs.base_url = localInputs.base_url.slice(0, localInputs.base_url.length - 1);
  188. }
  189. if (localInputs.type === 3 && localInputs.other === '') {
  190. localInputs.other = '2023-06-01-preview';
  191. }
  192. if (localInputs.type === 18 && localInputs.other === '') {
  193. localInputs.other = 'v2.1';
  194. }
  195. let res;
  196. if (!Array.isArray(localInputs.models)) {
  197. showError('提交失败,请勿重复提交!');
  198. handleCancel();
  199. return;
  200. }
  201. localInputs.models = localInputs.models.join(',');
  202. localInputs.group = localInputs.groups.join(',');
  203. if (isEdit) {
  204. res = await API.put(`/api/channel/`, {...localInputs, id: parseInt(channelId)});
  205. } else {
  206. res = await API.post(`/api/channel/`, localInputs);
  207. }
  208. const {success, message} = res.data;
  209. if (success) {
  210. if (isEdit) {
  211. showSuccess('渠道更新成功!');
  212. } else {
  213. showSuccess('渠道创建成功!');
  214. setInputs(originInputs);
  215. }
  216. props.refresh();
  217. props.handleClose();
  218. } else {
  219. showError(message);
  220. }
  221. };
  222. const addCustomModel = () => {
  223. if (customModel.trim() === '') return;
  224. if (inputs.models.includes(customModel)) return;
  225. let localModels = [...inputs.models];
  226. localModels.push(customModel);
  227. let localModelOptions = [];
  228. localModelOptions.push({
  229. key: customModel,
  230. text: customModel,
  231. value: customModel
  232. });
  233. setModelOptions(modelOptions => {
  234. return [...modelOptions, ...localModelOptions];
  235. });
  236. setCustomModel('');
  237. handleInputChange('models', localModels);
  238. };
  239. return (
  240. <>
  241. <SideSheet
  242. maskClosable={false}
  243. placement={isEdit ? 'right' : 'left'}
  244. title={<Title level={3}>{isEdit ? '更新渠道信息' : '创建新的渠道'}</Title>}
  245. headerStyle={{borderBottom: '1px solid var(--semi-color-border)'}}
  246. bodyStyle={{borderBottom: '1px solid var(--semi-color-border)'}}
  247. visible={props.visible}
  248. footer={
  249. <div style={{display: 'flex', justifyContent: 'flex-end'}}>
  250. <Space>
  251. <Button theme='solid' size={'large'} onClick={submit}>提交</Button>
  252. <Button theme='solid' size={'large'} type={'tertiary'} onClick={handleCancel}>取消</Button>
  253. </Space>
  254. </div>
  255. }
  256. closeIcon={null}
  257. onCancel={() => handleCancel()}
  258. width={isMobile() ? '100%' : 600}
  259. >
  260. <Spin spinning={loading}>
  261. <div style={{marginTop: 10}}>
  262. <Typography.Text strong>类型:</Typography.Text>
  263. </div>
  264. <Select
  265. name='type'
  266. required
  267. optionList={CHANNEL_OPTIONS}
  268. value={inputs.type}
  269. onChange={value => handleInputChange('type', value)}
  270. style={{width: '50%'}}
  271. />
  272. {
  273. inputs.type === 3 && (
  274. <>
  275. <div style={{marginTop: 10}}>
  276. <Banner type={"warning"} description={
  277. <>
  278. 注意,<strong>模型部署名称必须和模型名称保持一致</strong>,因为 One API 会把请求体中的
  279. model
  280. 参数替换为你的部署名称(模型名称中的点会被剔除),<a target='_blank'
  281. href='https://github.com/songquanpeng/one-api/issues/133?notification_referrer_id=NT_kwDOAmJSYrM2NjIwMzI3NDgyOjM5OTk4MDUw#issuecomment-1571602271'>图片演示</a>。
  282. </>
  283. }>
  284. </Banner>
  285. </div>
  286. <div style={{marginTop: 10}}>
  287. <Typography.Text strong>AZURE_OPENAI_ENDPOINT:</Typography.Text>
  288. </div>
  289. <Input
  290. label='AZURE_OPENAI_ENDPOINT'
  291. name='azure_base_url'
  292. placeholder={'请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com'}
  293. onChange={value => {
  294. handleInputChange('base_url', value)
  295. }}
  296. value={inputs.base_url}
  297. autoComplete='new-password'
  298. />
  299. <div style={{marginTop: 10}}>
  300. <Typography.Text strong>默认 API 版本:</Typography.Text>
  301. </div>
  302. <Input
  303. label='默认 API 版本'
  304. name='azure_other'
  305. placeholder={'请输入默认 API 版本,例如:2023-06-01-preview,该配置可以被实际的请求查询参数所覆盖'}
  306. onChange={value => {
  307. handleInputChange('other', value)
  308. }}
  309. value={inputs.other}
  310. autoComplete='new-password'
  311. />
  312. </>
  313. )
  314. }
  315. {
  316. inputs.type === 8 && (
  317. <>
  318. <div style={{marginTop: 10}}>
  319. <Typography.Text strong>Base URL:</Typography.Text>
  320. </div>
  321. <Input
  322. name='base_url'
  323. placeholder={'请输入自定义渠道的 Base URL'}
  324. onChange={value => {
  325. handleInputChange('base_url', value)
  326. }}
  327. value={inputs.base_url}
  328. autoComplete='new-password'
  329. />
  330. </>
  331. )
  332. }
  333. <div style={{marginTop: 10}}>
  334. <Typography.Text strong>名称:</Typography.Text>
  335. </div>
  336. <Input
  337. required
  338. name='name'
  339. placeholder={'请为渠道命名'}
  340. onChange={value => {
  341. handleInputChange('name', value)
  342. }}
  343. value={inputs.name}
  344. autoComplete='new-password'
  345. />
  346. <div style={{marginTop: 10}}>
  347. <Typography.Text strong>分组:</Typography.Text>
  348. </div>
  349. <Select
  350. placeholder={'请选择可以使用该渠道的分组'}
  351. name='groups'
  352. required
  353. multiple
  354. selection
  355. allowAdditions
  356. additionLabel={'请在系统设置页面编辑分组倍率以添加新的分组:'}
  357. onChange={value => {
  358. handleInputChange('groups', value)
  359. }}
  360. value={inputs.groups}
  361. autoComplete='new-password'
  362. optionList={groupOptions}
  363. />
  364. {
  365. inputs.type === 18 && (
  366. <>
  367. <div style={{marginTop: 10}}>
  368. <Typography.Text strong>模型版本:</Typography.Text>
  369. </div>
  370. <Input
  371. name='other'
  372. placeholder={'请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1'}
  373. onChange={value => {
  374. handleInputChange('other', value)
  375. }}
  376. value={inputs.other}
  377. autoComplete='new-password'
  378. />
  379. </>
  380. )
  381. }
  382. {
  383. inputs.type === 21 && (
  384. <>
  385. <div style={{marginTop: 10}}>
  386. <Typography.Text strong>知识库 ID:</Typography.Text>
  387. </div>
  388. <Input
  389. label='知识库 ID'
  390. name='other'
  391. placeholder={'请输入知识库 ID,例如:123456'}
  392. onChange={value => {
  393. handleInputChange('other', value)
  394. }}
  395. value={inputs.other}
  396. autoComplete='new-password'
  397. />
  398. </>
  399. )
  400. }
  401. <div style={{marginTop: 10}}>
  402. <Typography.Text strong>模型:</Typography.Text>
  403. </div>
  404. <Select
  405. placeholder={'请选择该渠道所支持的模型'}
  406. name='models'
  407. required
  408. multiple
  409. selection
  410. onChange={value => {
  411. handleInputChange('models', value)
  412. }}
  413. value={inputs.models}
  414. autoComplete='new-password'
  415. optionList={modelOptions}
  416. />
  417. <div style={{lineHeight: '40px', marginBottom: '12px'}}>
  418. <Space>
  419. <Button type='primary' onClick={() => {
  420. handleInputChange('models', basicModels);
  421. }}>填入基础模型</Button>
  422. <Button type='secondary' onClick={() => {
  423. handleInputChange('models', fullModels);
  424. }}>填入所有模型</Button>
  425. <Button type='warning' onClick={() => {
  426. handleInputChange('models', []);
  427. }}>清除所有模型</Button>
  428. </Space>
  429. <Input
  430. addonAfter={
  431. <Button type='primary' onClick={addCustomModel}>填入</Button>
  432. }
  433. placeholder='输入自定义模型名称'
  434. value={customModel}
  435. onChange={(value) => {
  436. setCustomModel(value);
  437. }}
  438. />
  439. </div>
  440. <div style={{marginTop: 10}}>
  441. <Typography.Text strong>模型重定向:</Typography.Text>
  442. </div>
  443. <TextArea
  444. placeholder={`此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`}
  445. name='model_mapping'
  446. onChange={value => {
  447. handleInputChange('model_mapping', value)
  448. }}
  449. autosize
  450. value={inputs.model_mapping}
  451. autoComplete='new-password'
  452. />
  453. <Typography.Text style={{
  454. color: 'rgba(var(--semi-blue-5), 1)',
  455. userSelect: 'none',
  456. cursor: 'pointer'
  457. }} onClick={
  458. () => {
  459. handleInputChange('model_mapping', JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2))
  460. }
  461. }>
  462. 填入模板
  463. </Typography.Text>
  464. <div style={{marginTop: 10}}>
  465. <Typography.Text strong>密钥:</Typography.Text>
  466. </div>
  467. {
  468. batch ?
  469. <TextArea
  470. label='密钥'
  471. name='key'
  472. required
  473. placeholder={'请输入密钥,一行一个'}
  474. onChange={value => {
  475. handleInputChange('key', value)
  476. }}
  477. value={inputs.key}
  478. style={{minHeight: 150, fontFamily: 'JetBrains Mono, Consolas'}}
  479. autoComplete='new-password'
  480. />
  481. :
  482. <Input
  483. label='密钥'
  484. name='key'
  485. required
  486. placeholder={type2secretPrompt(inputs.type)}
  487. onChange={value => {
  488. handleInputChange('key', value)
  489. }}
  490. value={inputs.key}
  491. autoComplete='new-password'
  492. />
  493. }
  494. <div style={{marginTop: 10}}>
  495. <Typography.Text strong>组织:</Typography.Text>
  496. </div>
  497. <Input
  498. label='组织,可选,不填则为默认组织'
  499. name='openai_organization'
  500. placeholder='请输入组织org-xxx'
  501. onChange={value => {
  502. handleInputChange('openai_organization', value)
  503. }}
  504. value={inputs.openai_organization}
  505. />
  506. <div style={{marginTop: 10, display: 'flex'}}>
  507. <Space>
  508. <Checkbox
  509. name='auto_ban'
  510. checked={autoBan}
  511. onChange={
  512. () => {
  513. setAutoBan(!autoBan);
  514. }
  515. }
  516. // onChange={handleInputChange}
  517. />
  518. <Typography.Text
  519. strong>是否自动禁用(仅当自动禁用开启时有效),关闭后不会自动禁用该渠道:</Typography.Text>
  520. </Space>
  521. </div>
  522. {
  523. !isEdit && (
  524. <div style={{marginTop: 10, display: 'flex'}}>
  525. <Space>
  526. <Checkbox
  527. checked={batch}
  528. label='批量创建'
  529. name='batch'
  530. onChange={() => setBatch(!batch)}
  531. />
  532. <Typography.Text strong>批量创建</Typography.Text>
  533. </Space>
  534. </div>
  535. )
  536. }
  537. {
  538. inputs.type !== 3 && inputs.type !== 8 && inputs.type !== 22 && (
  539. <>
  540. <div style={{marginTop: 10}}>
  541. <Typography.Text strong>代理:</Typography.Text>
  542. </div>
  543. <Input
  544. label='代理'
  545. name='base_url'
  546. placeholder={'此项可选,用于通过代理站来进行 API 调用'}
  547. onChange={value => {
  548. handleInputChange('base_url', value)
  549. }}
  550. value={inputs.base_url}
  551. autoComplete='new-password'
  552. />
  553. </>
  554. )
  555. }
  556. {
  557. inputs.type === 22 && (
  558. <>
  559. <div style={{marginTop: 10}}>
  560. <Typography.Text strong>私有部署地址:</Typography.Text>
  561. </div>
  562. <Input
  563. name='base_url'
  564. placeholder={'请输入私有部署地址,格式为:https://fastgpt.run/api/openapi'}
  565. onChange={value => {
  566. handleInputChange('base_url', value)
  567. }}
  568. value={inputs.base_url}
  569. autoComplete='new-password'
  570. />
  571. </>
  572. )
  573. }
  574. </Spin>
  575. </SideSheet>
  576. </>
  577. );
  578. };
  579. export default EditChannel;