EditChannelModal.jsx 61 KB

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