EditChannel.js 26 KB

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