EditChannelModal.jsx 55 KB

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