EditChannelModal.jsx 61 KB

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