EditChannelModal.jsx 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import React, { useEffect, useState, useRef, useMemo } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import {
  18. API,
  19. showError,
  20. showInfo,
  21. showSuccess,
  22. verifyJSON,
  23. } from '../../../../helpers';
  24. import { useIsMobile } from '../../../../hooks/common/useIsMobile.js';
  25. import { CHANNEL_OPTIONS } from '../../../../constants';
  26. import {
  27. SideSheet,
  28. Space,
  29. Spin,
  30. Button,
  31. Typography,
  32. Checkbox,
  33. Banner,
  34. Modal,
  35. ImagePreview,
  36. Card,
  37. Tag,
  38. Avatar,
  39. Form,
  40. Row,
  41. Col,
  42. Highlight,
  43. } from '@douyinfe/semi-ui';
  44. import { getChannelModels, copy, getChannelIcon, getModelCategories, modelSelectFilter } from '../../../../helpers';
  45. import {
  46. IconSave,
  47. IconClose,
  48. IconServer,
  49. IconSetting,
  50. IconCode,
  51. IconGlobe,
  52. IconBolt,
  53. } from '@douyinfe/semi-icons';
  54. const { Text, Title } = Typography;
  55. const MODEL_MAPPING_EXAMPLE = {
  56. 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
  57. };
  58. const STATUS_CODE_MAPPING_EXAMPLE = {
  59. 400: '500',
  60. };
  61. const REGION_EXAMPLE = {
  62. default: 'us-central1',
  63. 'claude-3-5-sonnet-20240620': 'europe-west1',
  64. };
  65. function type2secretPrompt(type) {
  66. // inputs.type === 15 ? '按照如下格式输入:APIKey|SecretKey' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥')
  67. switch (type) {
  68. case 15:
  69. return '按照如下格式输入:APIKey|SecretKey';
  70. case 18:
  71. return '按照如下格式输入:APPID|APISecret|APIKey';
  72. case 22:
  73. return '按照如下格式输入:APIKey-AppId,例如:fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041';
  74. case 23:
  75. return '按照如下格式输入:AppId|SecretId|SecretKey';
  76. case 33:
  77. return '按照如下格式输入:Ak|Sk|Region';
  78. case 50:
  79. return '按照如下格式输入: AccessKey|SecretKey, 如果上游是New API,则直接输ApiKey';
  80. case 51:
  81. return '按照如下格式输入: Access Key ID|Secret Access Key';
  82. default:
  83. return '请输入渠道对应的鉴权密钥';
  84. }
  85. }
  86. const EditChannelModal = (props) => {
  87. const { t } = useTranslation();
  88. const channelId = props.editingChannel.id;
  89. const isEdit = channelId !== undefined;
  90. const [loading, setLoading] = useState(isEdit);
  91. const isMobile = useIsMobile();
  92. const handleCancel = () => {
  93. props.handleClose();
  94. };
  95. const originInputs = {
  96. name: '',
  97. type: 1,
  98. key: '',
  99. openai_organization: '',
  100. max_input_tokens: 0,
  101. base_url: '',
  102. other: '',
  103. model_mapping: '',
  104. status_code_mapping: '',
  105. models: [],
  106. auto_ban: 1,
  107. test_model: '',
  108. groups: ['default'],
  109. priority: 0,
  110. weight: 0,
  111. tag: '',
  112. multi_key_mode: 'random',
  113. };
  114. const [batch, setBatch] = useState(false);
  115. const [multiToSingle, setMultiToSingle] = useState(false);
  116. const [multiKeyMode, setMultiKeyMode] = useState('random');
  117. const [autoBan, setAutoBan] = useState(true);
  118. const [inputs, setInputs] = useState(originInputs);
  119. const [originModelOptions, setOriginModelOptions] = useState([]);
  120. const [modelOptions, setModelOptions] = useState([]);
  121. const [groupOptions, setGroupOptions] = useState([]);
  122. const [basicModels, setBasicModels] = useState([]);
  123. const [fullModels, setFullModels] = useState([]);
  124. const [customModel, setCustomModel] = useState('');
  125. const [modalImageUrl, setModalImageUrl] = useState('');
  126. const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  127. const formApiRef = useRef(null);
  128. const [vertexKeys, setVertexKeys] = useState([]);
  129. const [vertexFileList, setVertexFileList] = useState([]);
  130. const vertexErroredNames = useRef(new Set()); // 避免重复报错
  131. const [isMultiKeyChannel, setIsMultiKeyChannel] = useState(false);
  132. const [channelSearchValue, setChannelSearchValue] = useState('');
  133. const [useManualInput, setUseManualInput] = useState(false); // 是否使用手动输入模式
  134. const getInitValues = () => ({ ...originInputs });
  135. const handleInputChange = (name, value) => {
  136. if (formApiRef.current) {
  137. formApiRef.current.setValue(name, value);
  138. }
  139. if (name === 'models' && Array.isArray(value)) {
  140. value = Array.from(new Set(value.map((m) => (m || '').trim())));
  141. }
  142. if (name === 'base_url' && value.endsWith('/v1')) {
  143. Modal.confirm({
  144. title: '警告',
  145. content:
  146. '不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?',
  147. onOk: () => {
  148. setInputs((inputs) => ({ ...inputs, [name]: value }));
  149. },
  150. });
  151. return;
  152. }
  153. setInputs((inputs) => ({ ...inputs, [name]: value }));
  154. if (name === 'type') {
  155. let localModels = [];
  156. switch (value) {
  157. case 2:
  158. localModels = [
  159. 'mj_imagine',
  160. 'mj_variation',
  161. 'mj_reroll',
  162. 'mj_blend',
  163. 'mj_upscale',
  164. 'mj_describe',
  165. 'mj_uploads',
  166. ];
  167. break;
  168. case 5:
  169. localModels = [
  170. 'swap_face',
  171. 'mj_imagine',
  172. 'mj_video',
  173. 'mj_edits',
  174. 'mj_variation',
  175. 'mj_reroll',
  176. 'mj_blend',
  177. 'mj_upscale',
  178. 'mj_describe',
  179. 'mj_zoom',
  180. 'mj_shorten',
  181. 'mj_modal',
  182. 'mj_inpaint',
  183. 'mj_custom_zoom',
  184. 'mj_high_variation',
  185. 'mj_low_variation',
  186. 'mj_pan',
  187. 'mj_uploads',
  188. ];
  189. break;
  190. case 36:
  191. localModels = ['suno_music', 'suno_lyrics'];
  192. break;
  193. default:
  194. localModels = getChannelModels(value);
  195. break;
  196. }
  197. if (inputs.models.length === 0) {
  198. setInputs((inputs) => ({ ...inputs, models: localModels }));
  199. }
  200. setBasicModels(localModels);
  201. // 重置手动输入模式状态
  202. setUseManualInput(false);
  203. }
  204. //setAutoBan
  205. };
  206. const loadChannel = async () => {
  207. setLoading(true);
  208. let res = await API.get(`/api/channel/${channelId}`);
  209. if (res === undefined) {
  210. return;
  211. }
  212. const { success, message, data } = res.data;
  213. if (success) {
  214. if (data.models === '') {
  215. data.models = [];
  216. } else {
  217. data.models = data.models.split(',');
  218. }
  219. if (data.group === '') {
  220. data.groups = [];
  221. } else {
  222. data.groups = data.group.split(',');
  223. }
  224. if (data.model_mapping !== '') {
  225. data.model_mapping = JSON.stringify(
  226. JSON.parse(data.model_mapping),
  227. null,
  228. 2,
  229. );
  230. }
  231. const chInfo = data.channel_info || {};
  232. const isMulti = chInfo.is_multi_key === true;
  233. setIsMultiKeyChannel(isMulti);
  234. if (isMulti) {
  235. setBatch(true);
  236. setMultiToSingle(true);
  237. const modeVal = chInfo.multi_key_mode || 'random';
  238. setMultiKeyMode(modeVal);
  239. data.multi_key_mode = modeVal;
  240. } else {
  241. setBatch(false);
  242. setMultiToSingle(false);
  243. }
  244. setInputs(data);
  245. if (formApiRef.current) {
  246. formApiRef.current.setValues(data);
  247. }
  248. if (data.auto_ban === 0) {
  249. setAutoBan(false);
  250. } else {
  251. setAutoBan(true);
  252. }
  253. setBasicModels(getChannelModels(data.type));
  254. // console.log(data);
  255. } else {
  256. showError(message);
  257. }
  258. setLoading(false);
  259. };
  260. const fetchUpstreamModelList = async (name) => {
  261. // if (inputs['type'] !== 1) {
  262. // showError(t('仅支持 OpenAI 接口格式'));
  263. // return;
  264. // }
  265. setLoading(true);
  266. const models = inputs['models'] || [];
  267. let err = false;
  268. if (isEdit) {
  269. // 如果是编辑模式,使用已有的 channelId 获取模型列表
  270. const res = await API.get('/api/channel/fetch_models/' + channelId, { skipErrorHandler: true });
  271. if (res && res.data && res.data.success) {
  272. models.push(...res.data.data);
  273. } else {
  274. err = true;
  275. }
  276. } else {
  277. // 如果是新建模式,通过后端代理获取模型列表
  278. if (!inputs?.['key']) {
  279. showError(t('请填写密钥'));
  280. err = true;
  281. } else {
  282. try {
  283. const res = await API.post(
  284. '/api/channel/fetch_models',
  285. {
  286. base_url: inputs['base_url'],
  287. type: inputs['type'],
  288. key: inputs['key'],
  289. },
  290. { skipErrorHandler: true },
  291. );
  292. if (res && res.data && res.data.success) {
  293. models.push(...res.data.data);
  294. } else {
  295. err = true;
  296. }
  297. } catch (error) {
  298. console.error('Error fetching models:', error);
  299. err = true;
  300. }
  301. }
  302. }
  303. if (!err) {
  304. handleInputChange(name, Array.from(new Set(models)));
  305. showSuccess(t('获取模型列表成功'));
  306. } else {
  307. showError(t('获取模型列表失败'));
  308. }
  309. setLoading(false);
  310. };
  311. const fetchModels = async () => {
  312. try {
  313. let res = await API.get(`/api/channel/models`);
  314. const localModelOptions = res.data.data.map((model) => {
  315. const id = (model.id || '').trim();
  316. return {
  317. key: id,
  318. label: id,
  319. value: id,
  320. };
  321. });
  322. setOriginModelOptions(localModelOptions);
  323. setFullModels(res.data.data.map((model) => model.id));
  324. setBasicModels(
  325. res.data.data
  326. .filter((model) => {
  327. return model.id.startsWith('gpt-') || model.id.startsWith('text-');
  328. })
  329. .map((model) => model.id),
  330. );
  331. } catch (error) {
  332. showError(error.message);
  333. }
  334. };
  335. const fetchGroups = async () => {
  336. try {
  337. let res = await API.get(`/api/group/`);
  338. if (res === undefined) {
  339. return;
  340. }
  341. setGroupOptions(
  342. res.data.data.map((group) => ({
  343. label: group,
  344. value: group,
  345. })),
  346. );
  347. } catch (error) {
  348. showError(error.message);
  349. }
  350. };
  351. useEffect(() => {
  352. const modelMap = new Map();
  353. originModelOptions.forEach((option) => {
  354. const v = (option.value || '').trim();
  355. if (!modelMap.has(v)) {
  356. modelMap.set(v, option);
  357. }
  358. });
  359. inputs.models.forEach((model) => {
  360. const v = (model || '').trim();
  361. if (!modelMap.has(v)) {
  362. modelMap.set(v, {
  363. key: v,
  364. label: v,
  365. value: v,
  366. });
  367. }
  368. });
  369. const categories = getModelCategories(t);
  370. const optionsWithIcon = Array.from(modelMap.values()).map((opt) => {
  371. const modelName = opt.value;
  372. let icon = null;
  373. for (const [key, category] of Object.entries(categories)) {
  374. if (key !== 'all' && category.filter({ model_name: modelName })) {
  375. icon = category.icon;
  376. break;
  377. }
  378. }
  379. return {
  380. ...opt,
  381. label: (
  382. <span className="flex items-center gap-1">
  383. {icon}
  384. {modelName}
  385. </span>
  386. ),
  387. };
  388. });
  389. setModelOptions(optionsWithIcon);
  390. }, [originModelOptions, inputs.models, t]);
  391. useEffect(() => {
  392. fetchModels().then();
  393. fetchGroups().then();
  394. if (!isEdit) {
  395. setInputs(originInputs);
  396. if (formApiRef.current) {
  397. formApiRef.current.setValues(originInputs);
  398. }
  399. let localModels = getChannelModels(inputs.type);
  400. setBasicModels(localModels);
  401. setInputs((inputs) => ({ ...inputs, models: localModels }));
  402. }
  403. }, [props.editingChannel.id]);
  404. useEffect(() => {
  405. if (formApiRef.current) {
  406. formApiRef.current.setValues(inputs);
  407. }
  408. }, [inputs]);
  409. useEffect(() => {
  410. if (props.visible) {
  411. if (isEdit) {
  412. loadChannel();
  413. } else {
  414. formApiRef.current?.setValues(getInitValues());
  415. }
  416. // 重置手动输入模式状态
  417. setUseManualInput(false);
  418. } else {
  419. formApiRef.current?.reset();
  420. }
  421. }, [props.visible, channelId]);
  422. const handleVertexUploadChange = ({ fileList }) => {
  423. vertexErroredNames.current.clear();
  424. (async () => {
  425. let validFiles = [];
  426. let keys = [];
  427. const errorNames = [];
  428. for (const item of fileList) {
  429. const fileObj = item.fileInstance;
  430. if (!fileObj) continue;
  431. try {
  432. const txt = await fileObj.text();
  433. keys.push(JSON.parse(txt));
  434. validFiles.push(item);
  435. } catch (err) {
  436. if (!vertexErroredNames.current.has(item.name)) {
  437. errorNames.push(item.name);
  438. vertexErroredNames.current.add(item.name);
  439. }
  440. }
  441. }
  442. // 非批量模式下只保留一个文件(最新选择的),避免重复叠加
  443. if (!batch && validFiles.length > 1) {
  444. validFiles = [validFiles[validFiles.length - 1]];
  445. keys = [keys[keys.length - 1]];
  446. }
  447. setVertexKeys(keys);
  448. setVertexFileList(validFiles);
  449. if (formApiRef.current) {
  450. formApiRef.current.setValue('vertex_files', validFiles);
  451. }
  452. setInputs((prev) => ({ ...prev, vertex_files: validFiles }));
  453. if (errorNames.length > 0) {
  454. showError(t('以下文件解析失败,已忽略:{{list}}', { list: errorNames.join(', ') }));
  455. }
  456. })();
  457. };
  458. const submit = async () => {
  459. const formValues = formApiRef.current ? formApiRef.current.getValues() : {};
  460. let localInputs = { ...formValues };
  461. if (localInputs.type === 41) {
  462. if (useManualInput) {
  463. // 手动输入模式
  464. if (localInputs.key && localInputs.key.trim() !== '') {
  465. try {
  466. // 验证 JSON 格式
  467. const parsedKey = JSON.parse(localInputs.key);
  468. // 确保是有效的密钥格式
  469. localInputs.key = JSON.stringify(parsedKey);
  470. } catch (err) {
  471. showError(t('密钥格式无效,请输入有效的 JSON 格式密钥'));
  472. return;
  473. }
  474. } else if (!isEdit) {
  475. showInfo(t('请输入密钥!'));
  476. return;
  477. }
  478. } else {
  479. // 文件上传模式
  480. let keys = vertexKeys;
  481. // 若当前未选择文件,尝试从已上传文件列表解析(异步读取)
  482. if (keys.length === 0 && vertexFileList.length > 0) {
  483. try {
  484. const parsed = await Promise.all(
  485. vertexFileList.map(async (item) => {
  486. const fileObj = item.fileInstance;
  487. if (!fileObj) return null;
  488. const txt = await fileObj.text();
  489. return JSON.parse(txt);
  490. })
  491. );
  492. keys = parsed.filter(Boolean);
  493. } catch (err) {
  494. showError(t('解析密钥文件失败: {{msg}}', { msg: err.message }));
  495. return;
  496. }
  497. }
  498. // 创建模式必须上传密钥;编辑模式可选
  499. if (keys.length === 0) {
  500. if (!isEdit) {
  501. showInfo(t('请上传密钥文件!'));
  502. return;
  503. } else {
  504. // 编辑模式且未上传新密钥,不修改 key
  505. delete localInputs.key;
  506. }
  507. } else {
  508. // 有新密钥,则覆盖
  509. if (batch) {
  510. localInputs.key = JSON.stringify(keys);
  511. } else {
  512. localInputs.key = JSON.stringify(keys[0]);
  513. }
  514. }
  515. }
  516. }
  517. // 如果是编辑模式且 key 为空字符串,避免提交空值覆盖旧密钥
  518. if (isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
  519. delete localInputs.key;
  520. }
  521. delete localInputs.vertex_files;
  522. if (!isEdit && (!localInputs.name || !localInputs.key)) {
  523. showInfo(t('请填写渠道名称和渠道密钥!'));
  524. return;
  525. }
  526. if (!Array.isArray(localInputs.models) || localInputs.models.length === 0) {
  527. showInfo(t('请至少选择一个模型!'));
  528. return;
  529. }
  530. if (localInputs.model_mapping && localInputs.model_mapping !== '' && !verifyJSON(localInputs.model_mapping)) {
  531. showInfo(t('模型映射必须是合法的 JSON 格式!'));
  532. return;
  533. }
  534. if (localInputs.base_url && localInputs.base_url.endsWith('/')) {
  535. localInputs.base_url = localInputs.base_url.slice(
  536. 0,
  537. localInputs.base_url.length - 1,
  538. );
  539. }
  540. if (localInputs.type === 18 && localInputs.other === '') {
  541. localInputs.other = 'v2.1';
  542. }
  543. let res;
  544. localInputs.auto_ban = localInputs.auto_ban ? 1 : 0;
  545. localInputs.models = localInputs.models.join(',');
  546. localInputs.group = (localInputs.groups || []).join(',');
  547. let mode = 'single';
  548. if (batch) {
  549. mode = multiToSingle ? 'multi_to_single' : 'batch';
  550. }
  551. if (isEdit) {
  552. res = await API.put(`/api/channel/`, {
  553. ...localInputs,
  554. id: parseInt(channelId),
  555. });
  556. } else {
  557. res = await API.post(`/api/channel/`, {
  558. mode: mode,
  559. multi_key_mode: mode === 'multi_to_single' ? multiKeyMode : undefined,
  560. channel: localInputs,
  561. });
  562. }
  563. const { success, message } = res.data;
  564. if (success) {
  565. if (isEdit) {
  566. showSuccess(t('渠道更新成功!'));
  567. } else {
  568. showSuccess(t('渠道创建成功!'));
  569. setInputs(originInputs);
  570. }
  571. props.refresh();
  572. props.handleClose();
  573. } else {
  574. showError(message);
  575. }
  576. };
  577. const addCustomModels = () => {
  578. if (customModel.trim() === '') return;
  579. const modelArray = customModel.split(',').map((model) => model.trim());
  580. let localModels = [...inputs.models];
  581. let localModelOptions = [...modelOptions];
  582. const addedModels = [];
  583. modelArray.forEach((model) => {
  584. if (model && !localModels.includes(model)) {
  585. localModels.push(model);
  586. localModelOptions.push({
  587. key: model,
  588. label: model,
  589. value: model,
  590. });
  591. addedModels.push(model);
  592. }
  593. });
  594. setModelOptions(localModelOptions);
  595. setCustomModel('');
  596. handleInputChange('models', localModels);
  597. if (addedModels.length > 0) {
  598. showSuccess(
  599. t('已新增 {{count}} 个模型:{{list}}', {
  600. count: addedModels.length,
  601. list: addedModels.join(', '),
  602. })
  603. );
  604. } else {
  605. showInfo(t('未发现新增模型'));
  606. }
  607. };
  608. const batchAllowed = !isEdit || isMultiKeyChannel;
  609. const batchExtra = batchAllowed ? (
  610. <Space>
  611. <Checkbox
  612. disabled={isEdit}
  613. checked={batch}
  614. onChange={(e) => {
  615. const checked = e.target.checked;
  616. if (!checked && vertexFileList.length > 1) {
  617. Modal.confirm({
  618. title: t('切换为单密钥模式'),
  619. content: t('将仅保留第一个密钥文件,其余文件将被移除,是否继续?'),
  620. onOk: () => {
  621. const firstFile = vertexFileList[0];
  622. const firstKey = vertexKeys[0] ? [vertexKeys[0]] : [];
  623. setVertexFileList([firstFile]);
  624. setVertexKeys(firstKey);
  625. formApiRef.current?.setValue('vertex_files', [firstFile]);
  626. setInputs((prev) => ({ ...prev, vertex_files: [firstFile] }));
  627. setBatch(false);
  628. setMultiToSingle(false);
  629. setMultiKeyMode('random');
  630. },
  631. onCancel: () => {
  632. setBatch(true);
  633. },
  634. centered: true,
  635. });
  636. return;
  637. }
  638. setBatch(checked);
  639. if (!checked) {
  640. setMultiToSingle(false);
  641. setMultiKeyMode('random');
  642. } else {
  643. // 批量模式下禁用手动输入,并清空手动输入的内容
  644. setUseManualInput(false);
  645. if (inputs.type === 41) {
  646. // 清空手动输入的密钥内容
  647. if (formApiRef.current) {
  648. formApiRef.current.setValue('key', '');
  649. }
  650. handleInputChange('key', '');
  651. }
  652. }
  653. }}
  654. >{t('批量创建')}</Checkbox>
  655. {/*{batch && (*/}
  656. {/* <Checkbox disabled={isEdit} checked={multiToSingle} onChange={() => {*/}
  657. {/* setMultiToSingle(prev => !prev);*/}
  658. {/* setInputs(prev => {*/}
  659. {/* const newInputs = { ...prev };*/}
  660. {/* if (!multiToSingle) {*/}
  661. {/* newInputs.multi_key_mode = multiKeyMode;*/}
  662. {/* } else {*/}
  663. {/* delete newInputs.multi_key_mode;*/}
  664. {/* }*/}
  665. {/* return newInputs;*/}
  666. {/* });*/}
  667. {/* }}>{t('密钥聚合模式')}</Checkbox>*/}
  668. {/*)}*/}
  669. </Space>
  670. ) : null;
  671. const channelOptionList = useMemo(
  672. () =>
  673. CHANNEL_OPTIONS.map((opt) => ({
  674. ...opt,
  675. // 保持 label 为纯文本以支持搜索
  676. label: opt.label,
  677. })),
  678. [],
  679. );
  680. const renderChannelOption = (renderProps) => {
  681. const {
  682. disabled,
  683. selected,
  684. label,
  685. value,
  686. focused,
  687. className,
  688. style,
  689. onMouseEnter,
  690. onClick,
  691. ...rest
  692. } = renderProps;
  693. const searchWords = channelSearchValue ? [channelSearchValue] : [];
  694. // 构建样式类名
  695. const optionClassName = [
  696. 'flex items-center gap-3 px-3 py-2 transition-all duration-200 rounded-lg mx-2 my-1',
  697. focused && 'bg-blue-50 shadow-sm',
  698. selected && 'bg-blue-100 text-blue-700 shadow-lg ring-2 ring-blue-200 ring-opacity-50',
  699. disabled && 'opacity-50 cursor-not-allowed',
  700. !disabled && 'hover:bg-gray-50 hover:shadow-md cursor-pointer',
  701. className
  702. ].filter(Boolean).join(' ');
  703. return (
  704. <div
  705. style={style}
  706. className={optionClassName}
  707. onClick={() => !disabled && onClick()}
  708. onMouseEnter={e => onMouseEnter()}
  709. >
  710. <div className="flex items-center gap-3 w-full">
  711. <div className="flex-shrink-0 w-5 h-5 flex items-center justify-center">
  712. {getChannelIcon(value)}
  713. </div>
  714. <div className="flex-1 min-w-0">
  715. <Highlight
  716. sourceString={label}
  717. searchWords={searchWords}
  718. className="text-sm font-medium truncate"
  719. />
  720. </div>
  721. {selected && (
  722. <div className="flex-shrink-0 text-blue-600">
  723. <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
  724. <path d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z" />
  725. </svg>
  726. </div>
  727. )}
  728. </div>
  729. </div>
  730. );
  731. };
  732. return (
  733. <>
  734. <SideSheet
  735. placement={isEdit ? 'right' : 'left'}
  736. title={
  737. <Space>
  738. <Tag color="blue" shape="circle">{isEdit ? t('编辑') : t('新建')}</Tag>
  739. <Title heading={4} className="m-0">
  740. {isEdit ? t('更新渠道信息') : t('创建新的渠道')}
  741. </Title>
  742. </Space>
  743. }
  744. bodyStyle={{ padding: '0' }}
  745. visible={props.visible}
  746. width={isMobile ? '100%' : 600}
  747. footer={
  748. <div className="flex justify-end bg-white">
  749. <Space>
  750. <Button
  751. theme="solid"
  752. onClick={() => formApiRef.current?.submitForm()}
  753. icon={<IconSave />}
  754. >
  755. {t('提交')}
  756. </Button>
  757. <Button
  758. theme="light"
  759. type="primary"
  760. onClick={handleCancel}
  761. icon={<IconClose />}
  762. >
  763. {t('取消')}
  764. </Button>
  765. </Space>
  766. </div>
  767. }
  768. closeIcon={null}
  769. onCancel={() => handleCancel()}
  770. >
  771. <Form
  772. key={isEdit ? 'edit' : 'new'}
  773. initValues={originInputs}
  774. getFormApi={(api) => (formApiRef.current = api)}
  775. onSubmit={submit}
  776. >
  777. {() => (
  778. <Spin spinning={loading}>
  779. <div className="p-2">
  780. <Card className="!rounded-2xl shadow-sm border-0 mb-6">
  781. {/* Header: Basic Info */}
  782. <div className="flex items-center mb-2">
  783. <Avatar size="small" color="blue" className="mr-2 shadow-md">
  784. <IconServer size={16} />
  785. </Avatar>
  786. <div>
  787. <Text className="text-lg font-medium">{t('基本信息')}</Text>
  788. <div className="text-xs text-gray-600">{t('渠道的基本配置信息')}</div>
  789. </div>
  790. </div>
  791. <Form.Select
  792. field='type'
  793. label={t('类型')}
  794. placeholder={t('请选择渠道类型')}
  795. rules={[{ required: true, message: t('请选择渠道类型') }]}
  796. optionList={channelOptionList}
  797. style={{ width: '100%' }}
  798. filter={modelSelectFilter}
  799. autoClearSearchValue={false}
  800. searchPosition='dropdown'
  801. onSearch={(value) => setChannelSearchValue(value)}
  802. renderOptionItem={renderChannelOption}
  803. onChange={(value) => handleInputChange('type', value)}
  804. />
  805. <Form.Input
  806. field='name'
  807. label={t('名称')}
  808. placeholder={t('请为渠道命名')}
  809. rules={[{ required: true, message: t('请为渠道命名') }]}
  810. showClear
  811. onChange={(value) => handleInputChange('name', value)}
  812. autoComplete='new-password'
  813. />
  814. {batch ? (
  815. inputs.type === 41 ? (
  816. <Form.Upload
  817. field='vertex_files'
  818. label={t('密钥文件 (.json)')}
  819. accept='.json'
  820. multiple
  821. draggable
  822. dragIcon={<IconBolt />}
  823. dragMainText={t('点击上传文件或拖拽文件到这里')}
  824. dragSubText={t('仅支持 JSON 文件,支持多文件')}
  825. style={{ marginTop: 10 }}
  826. uploadTrigger='custom'
  827. beforeUpload={() => false}
  828. onChange={handleVertexUploadChange}
  829. fileList={vertexFileList}
  830. rules={isEdit ? [] : [{ required: true, message: t('请上传密钥文件') }]}
  831. extraText={batchExtra}
  832. />
  833. ) : (
  834. <Form.TextArea
  835. field='key'
  836. label={t('密钥')}
  837. placeholder={t('请输入密钥,一行一个')}
  838. rules={isEdit ? [] : [{ required: true, message: t('请输入密钥') }]}
  839. autosize
  840. autoComplete='new-password'
  841. onChange={(value) => handleInputChange('key', value)}
  842. extraText={batchExtra}
  843. showClear
  844. />
  845. )
  846. ) : (
  847. <>
  848. {inputs.type === 41 ? (
  849. <>
  850. {!batch && (
  851. <div className="flex items-center justify-between mb-3">
  852. <Text className="text-sm font-medium">{t('密钥输入方式')}</Text>
  853. <Space>
  854. <Button
  855. size="small"
  856. type={!useManualInput ? 'primary' : 'tertiary'}
  857. onClick={() => {
  858. setUseManualInput(false);
  859. // 切换到文件上传模式时清空手动输入的密钥
  860. if (formApiRef.current) {
  861. formApiRef.current.setValue('key', '');
  862. }
  863. handleInputChange('key', '');
  864. }}
  865. >
  866. {t('文件上传')}
  867. </Button>
  868. <Button
  869. size="small"
  870. type={useManualInput ? 'primary' : 'tertiary'}
  871. onClick={() => {
  872. setUseManualInput(true);
  873. // 切换到手动输入模式时清空文件上传相关状态
  874. setVertexKeys([]);
  875. setVertexFileList([]);
  876. if (formApiRef.current) {
  877. formApiRef.current.setValue('vertex_files', []);
  878. }
  879. setInputs((prev) => ({ ...prev, vertex_files: [] }));
  880. }}
  881. >
  882. {t('手动输入')}
  883. </Button>
  884. </Space>
  885. </div>
  886. )}
  887. {batch && (
  888. <Banner
  889. type='info'
  890. description={t('批量创建模式下仅支持文件上传,不支持手动输入')}
  891. className='!rounded-lg mb-3'
  892. />
  893. )}
  894. {useManualInput && !batch ? (
  895. <Form.TextArea
  896. field='key'
  897. label={isEdit ? t('密钥(编辑模式下,保存的密钥不会显示)') : t('密钥')}
  898. placeholder={t('请输入 JSON 格式的密钥内容,例如:\n{\n "type": "service_account",\n "project_id": "your-project-id",\n "private_key_id": "...",\n "private_key": "...",\n "client_email": "...",\n "client_id": "...",\n "auth_uri": "...",\n "token_uri": "...",\n "auth_provider_x509_cert_url": "...",\n "client_x509_cert_url": "..."\n}')}
  899. rules={isEdit ? [] : [{ required: true, message: t('请输入密钥') }]}
  900. autoComplete='new-password'
  901. onChange={(value) => handleInputChange('key', value)}
  902. extraText={
  903. <div className="flex items-center gap-2">
  904. <Text type="tertiary" size="small">
  905. {t('请输入完整的 JSON 格式密钥内容')}
  906. </Text>
  907. {batchExtra}
  908. </div>
  909. }
  910. autosize
  911. showClear
  912. />
  913. ) : (
  914. <Form.Upload
  915. field='vertex_files'
  916. label={t('密钥文件 (.json)')}
  917. accept='.json'
  918. draggable
  919. dragIcon={<IconBolt />}
  920. dragMainText={t('点击上传文件或拖拽文件到这里')}
  921. dragSubText={t('仅支持 JSON 文件')}
  922. style={{ marginTop: 10 }}
  923. uploadTrigger='custom'
  924. beforeUpload={() => false}
  925. onChange={handleVertexUploadChange}
  926. fileList={vertexFileList}
  927. rules={isEdit ? [] : [{ required: true, message: t('请上传密钥文件') }]}
  928. extraText={batchExtra}
  929. />
  930. )}
  931. </>
  932. ) : (
  933. <Form.Input
  934. field='key'
  935. label={isEdit ? t('密钥(编辑模式下,保存的密钥不会显示)') : t('密钥')}
  936. placeholder={t(type2secretPrompt(inputs.type))}
  937. rules={isEdit ? [] : [{ required: true, message: t('请输入密钥') }]}
  938. autoComplete='new-password'
  939. onChange={(value) => handleInputChange('key', value)}
  940. extraText={batchExtra}
  941. showClear
  942. />
  943. )}
  944. </>
  945. )}
  946. {batch && multiToSingle && (
  947. <>
  948. <Form.Select
  949. field='multi_key_mode'
  950. label={t('密钥聚合模式')}
  951. placeholder={t('请选择多密钥使用策略')}
  952. optionList={[
  953. { label: t('随机'), value: 'random' },
  954. { label: t('轮询'), value: 'polling' },
  955. ]}
  956. style={{ width: '100%' }}
  957. value={inputs.multi_key_mode || 'random'}
  958. onChange={(value) => {
  959. setMultiKeyMode(value);
  960. handleInputChange('multi_key_mode', value);
  961. }}
  962. />
  963. {inputs.multi_key_mode === 'polling' && (
  964. <Banner
  965. type='warning'
  966. description={t('轮询模式必须搭配Redis和内存缓存功能使用,否则性能将大幅降低,并且无法实现轮询功能')}
  967. className='!rounded-lg mt-2'
  968. />
  969. )}
  970. </>
  971. )}
  972. {inputs.type === 18 && (
  973. <Form.Input
  974. field='other'
  975. label={t('模型版本')}
  976. placeholder={'请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1'}
  977. onChange={(value) => handleInputChange('other', value)}
  978. showClear
  979. />
  980. )}
  981. {inputs.type === 41 && (
  982. <Form.TextArea
  983. field='other'
  984. label={t('部署地区')}
  985. placeholder={t(
  986. '请输入部署地区,例如:us-central1\n支持使用模型映射格式\n{\n "default": "us-central1",\n "claude-3-5-sonnet-20240620": "europe-west1"\n}'
  987. )}
  988. autosize
  989. onChange={(value) => handleInputChange('other', value)}
  990. rules={[{ required: true, message: t('请填写部署地区') }]}
  991. extraText={
  992. <Text
  993. className="!text-semi-color-primary cursor-pointer"
  994. onClick={() => handleInputChange('other', JSON.stringify(REGION_EXAMPLE, null, 2))}
  995. >
  996. {t('填入模板')}
  997. </Text>
  998. }
  999. showClear
  1000. />
  1001. )}
  1002. {inputs.type === 21 && (
  1003. <Form.Input
  1004. field='other'
  1005. label={t('知识库 ID')}
  1006. placeholder={'请输入知识库 ID,例如:123456'}
  1007. onChange={(value) => handleInputChange('other', value)}
  1008. showClear
  1009. />
  1010. )}
  1011. {inputs.type === 39 && (
  1012. <Form.Input
  1013. field='other'
  1014. label='Account ID'
  1015. placeholder={'请输入Account ID,例如:d6b5da8hk1awo8nap34ube6gh'}
  1016. onChange={(value) => handleInputChange('other', value)}
  1017. showClear
  1018. />
  1019. )}
  1020. {inputs.type === 49 && (
  1021. <Form.Input
  1022. field='other'
  1023. label={t('智能体ID')}
  1024. placeholder={'请输入智能体ID,例如:7342866812345'}
  1025. onChange={(value) => handleInputChange('other', value)}
  1026. showClear
  1027. />
  1028. )}
  1029. {inputs.type === 1 && (
  1030. <Form.Input
  1031. field='openai_organization'
  1032. label={t('组织')}
  1033. placeholder={t('请输入组织org-xxx')}
  1034. showClear
  1035. helpText={t('组织,不填则为默认组织')}
  1036. onChange={(value) => handleInputChange('openai_organization', value)}
  1037. />
  1038. )}
  1039. </Card>
  1040. {/* API Configuration Card */}
  1041. <Card className="!rounded-2xl shadow-sm border-0 mb-6">
  1042. {/* Header: API Config */}
  1043. <div className="flex items-center mb-2">
  1044. <Avatar size="small" color="green" className="mr-2 shadow-md">
  1045. <IconGlobe size={16} />
  1046. </Avatar>
  1047. <div>
  1048. <Text className="text-lg font-medium">{t('API 配置')}</Text>
  1049. <div className="text-xs text-gray-600">{t('API 地址和相关配置')}</div>
  1050. </div>
  1051. </div>
  1052. {inputs.type === 40 && (
  1053. <Banner
  1054. type='info'
  1055. description={
  1056. <div>
  1057. <Text strong>{t('邀请链接')}:</Text>
  1058. <Text
  1059. link
  1060. underline
  1061. className="ml-2 cursor-pointer"
  1062. onClick={() => window.open('https://cloud.siliconflow.cn/i/hij0YNTZ')}
  1063. >
  1064. https://cloud.siliconflow.cn/i/hij0YNTZ
  1065. </Text>
  1066. </div>
  1067. }
  1068. className='!rounded-lg'
  1069. />
  1070. )}
  1071. {inputs.type === 3 && (
  1072. <>
  1073. <Banner
  1074. type='warning'
  1075. description={t('2025年5月10日后添加的渠道,不需要再在部署的时候移除模型名称中的"."')}
  1076. className='!rounded-lg'
  1077. />
  1078. <div>
  1079. <Form.Input
  1080. field='base_url'
  1081. label='AZURE_OPENAI_ENDPOINT'
  1082. placeholder={t('请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com')}
  1083. onChange={(value) => handleInputChange('base_url', value)}
  1084. showClear
  1085. />
  1086. </div>
  1087. <div>
  1088. <Form.Input
  1089. field='other'
  1090. label={t('默认 API 版本')}
  1091. placeholder={t('请输入默认 API 版本,例如:2025-04-01-preview')}
  1092. onChange={(value) => handleInputChange('other', value)}
  1093. showClear
  1094. />
  1095. </div>
  1096. </>
  1097. )}
  1098. {inputs.type === 8 && (
  1099. <>
  1100. <Banner
  1101. type='warning'
  1102. description={t('如果你对接的是上游One API或者New API等转发项目,请使用OpenAI类型,不要使用此类型,除非你知道你在做什么。')}
  1103. className='!rounded-lg'
  1104. />
  1105. <div>
  1106. <Form.Input
  1107. field='base_url'
  1108. label={t('完整的 Base URL,支持变量{model}')}
  1109. placeholder={t('请输入完整的URL,例如:https://api.openai.com/v1/chat/completions')}
  1110. onChange={(value) => handleInputChange('base_url', value)}
  1111. showClear
  1112. />
  1113. </div>
  1114. </>
  1115. )}
  1116. {inputs.type === 37 && (
  1117. <Banner
  1118. type='warning'
  1119. description={t('Dify渠道只适配chatflow和agent,并且agent不支持图片!')}
  1120. className='!rounded-lg'
  1121. />
  1122. )}
  1123. {inputs.type !== 3 && inputs.type !== 8 && inputs.type !== 22 && inputs.type !== 36 && inputs.type !== 45 && (
  1124. <div>
  1125. <Form.Input
  1126. field='base_url'
  1127. label={t('API地址')}
  1128. placeholder={t('此项可选,用于通过自定义API地址来进行 API 调用,末尾不要带/v1和/')}
  1129. onChange={(value) => handleInputChange('base_url', value)}
  1130. showClear
  1131. extraText={t('对于官方渠道,new-api已经内置地址,除非是第三方代理站点或者Azure的特殊接入地址,否则不需要填写')}
  1132. />
  1133. </div>
  1134. )}
  1135. {inputs.type === 22 && (
  1136. <div>
  1137. <Form.Input
  1138. field='base_url'
  1139. label={t('私有部署地址')}
  1140. placeholder={t('请输入私有部署地址,格式为:https://fastgpt.run/api/openapi')}
  1141. onChange={(value) => handleInputChange('base_url', value)}
  1142. showClear
  1143. />
  1144. </div>
  1145. )}
  1146. {inputs.type === 36 && (
  1147. <div>
  1148. <Form.Input
  1149. field='base_url'
  1150. label={t('注意非Chat API,请务必填写正确的API地址,否则可能导致无法使用')}
  1151. placeholder={t('请输入到 /suno 前的路径,通常就是域名,例如:https://api.example.com')}
  1152. onChange={(value) => handleInputChange('base_url', value)}
  1153. showClear
  1154. />
  1155. </div>
  1156. )}
  1157. </Card>
  1158. {/* Model Configuration Card */}
  1159. <Card className="!rounded-2xl shadow-sm border-0 mb-6">
  1160. {/* Header: Model Config */}
  1161. <div className="flex items-center mb-2">
  1162. <Avatar size="small" color="purple" className="mr-2 shadow-md">
  1163. <IconCode size={16} />
  1164. </Avatar>
  1165. <div>
  1166. <Text className="text-lg font-medium">{t('模型配置')}</Text>
  1167. <div className="text-xs text-gray-600">{t('模型选择和映射设置')}</div>
  1168. </div>
  1169. </div>
  1170. <Form.Select
  1171. field='models'
  1172. label={t('模型')}
  1173. placeholder={t('请选择该渠道所支持的模型')}
  1174. rules={[{ required: true, message: t('请选择模型') }]}
  1175. multiple
  1176. filter={modelSelectFilter}
  1177. autoClearSearchValue={false}
  1178. searchPosition='dropdown'
  1179. optionList={modelOptions}
  1180. style={{ width: '100%' }}
  1181. onChange={(value) => handleInputChange('models', value)}
  1182. extraText={(
  1183. <Space wrap>
  1184. <Button size='small' type='primary' onClick={() => handleInputChange('models', basicModels)}>
  1185. {t('填入相关模型')}
  1186. </Button>
  1187. <Button size='small' type='secondary' onClick={() => handleInputChange('models', fullModels)}>
  1188. {t('填入所有模型')}
  1189. </Button>
  1190. <Button size='small' type='tertiary' onClick={() => fetchUpstreamModelList('models')}>
  1191. {t('获取模型列表')}
  1192. </Button>
  1193. <Button size='small' type='warning' onClick={() => handleInputChange('models', [])}>
  1194. {t('清除所有模型')}
  1195. </Button>
  1196. <Button
  1197. size='small'
  1198. type='tertiary'
  1199. onClick={() => {
  1200. if (inputs.models.length === 0) {
  1201. showInfo(t('没有模型可以复制'));
  1202. return;
  1203. }
  1204. try {
  1205. copy(inputs.models.join(','));
  1206. showSuccess(t('模型列表已复制到剪贴板'));
  1207. } catch (error) {
  1208. showError(t('复制失败'));
  1209. }
  1210. }}
  1211. >
  1212. {t('复制所有模型')}
  1213. </Button>
  1214. </Space>
  1215. )}
  1216. />
  1217. <Form.Input
  1218. field='custom_model'
  1219. label={t('自定义模型名称')}
  1220. placeholder={t('输入自定义模型名称')}
  1221. onChange={(value) => setCustomModel(value.trim())}
  1222. value={customModel}
  1223. suffix={
  1224. <Button size='small' type='primary' onClick={addCustomModels}>
  1225. {t('填入')}
  1226. </Button>
  1227. }
  1228. />
  1229. <Form.Input
  1230. field='test_model'
  1231. label={t('默认测试模型')}
  1232. placeholder={t('不填则为模型列表第一个')}
  1233. onChange={(value) => handleInputChange('test_model', value)}
  1234. showClear
  1235. />
  1236. <Form.TextArea
  1237. field='model_mapping'
  1238. label={t('模型重定向')}
  1239. placeholder={
  1240. t('此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:') +
  1241. `\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`
  1242. }
  1243. autosize
  1244. onChange={(value) => handleInputChange('model_mapping', value)}
  1245. extraText={
  1246. <Text
  1247. className="!text-semi-color-primary cursor-pointer"
  1248. onClick={() => handleInputChange('model_mapping', JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2))}
  1249. >
  1250. {t('填入模板')}
  1251. </Text>
  1252. }
  1253. showClear
  1254. />
  1255. </Card>
  1256. {/* Advanced Settings Card */}
  1257. <Card className="!rounded-2xl shadow-sm border-0 mb-6">
  1258. {/* Header: Advanced Settings */}
  1259. <div className="flex items-center mb-2">
  1260. <Avatar size="small" color="orange" className="mr-2 shadow-md">
  1261. <IconSetting size={16} />
  1262. </Avatar>
  1263. <div>
  1264. <Text className="text-lg font-medium">{t('高级设置')}</Text>
  1265. <div className="text-xs text-gray-600">{t('渠道的高级配置选项')}</div>
  1266. </div>
  1267. </div>
  1268. <Form.Select
  1269. field='groups'
  1270. label={t('分组')}
  1271. placeholder={t('请选择可以使用该渠道的分组')}
  1272. multiple
  1273. allowAdditions
  1274. additionLabel={t('请在系统设置页面编辑分组倍率以添加新的分组:')}
  1275. optionList={groupOptions}
  1276. style={{ width: '100%' }}
  1277. onChange={(value) => handleInputChange('groups', value)}
  1278. />
  1279. <Form.Input
  1280. field='tag'
  1281. label={t('渠道标签')}
  1282. placeholder={t('渠道标签')}
  1283. showClear
  1284. onChange={(value) => handleInputChange('tag', value)}
  1285. />
  1286. <Row gutter={12}>
  1287. <Col span={12}>
  1288. <Form.InputNumber
  1289. field='priority'
  1290. label={t('渠道优先级')}
  1291. placeholder={t('渠道优先级')}
  1292. min={0}
  1293. onNumberChange={(value) => handleInputChange('priority', value)}
  1294. style={{ width: '100%' }}
  1295. />
  1296. </Col>
  1297. <Col span={12}>
  1298. <Form.InputNumber
  1299. field='weight'
  1300. label={t('渠道权重')}
  1301. placeholder={t('渠道权重')}
  1302. min={0}
  1303. onNumberChange={(value) => handleInputChange('weight', value)}
  1304. style={{ width: '100%' }}
  1305. />
  1306. </Col>
  1307. </Row>
  1308. <Form.Switch
  1309. field='auto_ban'
  1310. label={t('是否自动禁用')}
  1311. checkedText={t('开')}
  1312. uncheckedText={t('关')}
  1313. onChange={(val) => setAutoBan(val)}
  1314. extraText={t('仅当自动禁用开启时有效,关闭后不会自动禁用该渠道')}
  1315. initValue={autoBan}
  1316. />
  1317. <Form.TextArea
  1318. field='param_override'
  1319. label={t('参数覆盖')}
  1320. placeholder={
  1321. t('此项可选,用于覆盖请求参数。不支持覆盖 stream 参数。为一个 JSON 字符串,例如:') +
  1322. '\n{\n "temperature": 0\n}'
  1323. }
  1324. autosize
  1325. onChange={(value) => handleInputChange('param_override', value)}
  1326. extraText={
  1327. <Text
  1328. className="!text-semi-color-primary cursor-pointer"
  1329. onClick={() => handleInputChange('param_override', JSON.stringify({ temperature: 0 }, null, 2))}
  1330. >
  1331. {t('填入模板')}
  1332. </Text>
  1333. }
  1334. showClear
  1335. />
  1336. <Form.TextArea
  1337. field='status_code_mapping'
  1338. label={t('状态码复写')}
  1339. placeholder={
  1340. t('此项可选,用于复写返回的状态码,仅影响本地判断,不修改返回到上游的状态码,比如将claude渠道的400错误复写为500(用于重试),请勿滥用该功能,例如:') +
  1341. '\n' +
  1342. JSON.stringify(STATUS_CODE_MAPPING_EXAMPLE, null, 2)
  1343. }
  1344. autosize
  1345. onChange={(value) => handleInputChange('status_code_mapping', value)}
  1346. extraText={
  1347. <Text
  1348. className="!text-semi-color-primary cursor-pointer"
  1349. onClick={() => handleInputChange('status_code_mapping', JSON.stringify(STATUS_CODE_MAPPING_EXAMPLE, null, 2))}
  1350. >
  1351. {t('填入模板')}
  1352. </Text>
  1353. }
  1354. showClear
  1355. />
  1356. <Form.TextArea
  1357. field='setting'
  1358. label={t('渠道额外设置')}
  1359. placeholder={
  1360. t('此项可选,用于配置渠道特定设置,为一个 JSON 字符串,例如:') +
  1361. '\n{\n "force_format": true\n}'
  1362. }
  1363. autosize
  1364. onChange={(value) => handleInputChange('setting', value)}
  1365. extraText={(
  1366. <Space wrap>
  1367. <Text
  1368. className="!text-semi-color-primary cursor-pointer"
  1369. onClick={() => handleInputChange('setting', JSON.stringify({ force_format: true }, null, 2))}
  1370. >
  1371. {t('填入模板')}
  1372. </Text>
  1373. <Text
  1374. className="!text-semi-color-primary cursor-pointer"
  1375. onClick={() => window.open('https://github.com/QuantumNous/new-api/blob/main/docs/channel/other_setting.md')}
  1376. >
  1377. {t('设置说明')}
  1378. </Text>
  1379. </Space>
  1380. )}
  1381. showClear
  1382. />
  1383. </Card>
  1384. </div>
  1385. </Spin>
  1386. )}
  1387. </Form>
  1388. <ImagePreview
  1389. src={modalImageUrl}
  1390. visible={isModalOpenurl}
  1391. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  1392. />
  1393. </SideSheet>
  1394. </>
  1395. );
  1396. };
  1397. export default EditChannelModal;