EditChannelModal.jsx 64 KB

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