EditChannelModal.jsx 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488
  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';
  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. Input,
  44. } from '@douyinfe/semi-ui';
  45. import {
  46. getChannelModels,
  47. copy,
  48. getChannelIcon,
  49. getModelCategories,
  50. selectFilter,
  51. } from '../../../../helpers';
  52. import ModelSelectModal from './ModelSelectModal';
  53. import JSONEditor from '../../../common/ui/JSONEditor';
  54. import TwoFactorAuthModal from '../../../common/modals/TwoFactorAuthModal';
  55. import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay';
  56. import {
  57. IconSave,
  58. IconClose,
  59. IconServer,
  60. IconSetting,
  61. IconCode,
  62. IconGlobe,
  63. IconBolt,
  64. } from '@douyinfe/semi-icons';
  65. const { Text, Title } = Typography;
  66. const MODEL_MAPPING_EXAMPLE = {
  67. 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
  68. };
  69. const STATUS_CODE_MAPPING_EXAMPLE = {
  70. 400: '500',
  71. };
  72. const REGION_EXAMPLE = {
  73. default: 'global',
  74. 'gemini-1.5-pro-002': 'europe-west2',
  75. 'gemini-1.5-flash-002': 'europe-west2',
  76. 'claude-3-5-sonnet-20240620': 'europe-west1',
  77. };
  78. // 支持并且已适配通过接口获取模型列表的渠道类型
  79. const MODEL_FETCHABLE_TYPES = new Set([
  80. 1,
  81. 4,
  82. 14,
  83. 34,
  84. 17,
  85. 26,
  86. 24,
  87. 47,
  88. 25,
  89. 20,
  90. 23,
  91. 31,
  92. 35,
  93. 40,
  94. 42,
  95. 48,
  96. ]);
  97. function type2secretPrompt(type) {
  98. // inputs.type === 15 ? '按照如下格式输入:APIKey|SecretKey' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥')
  99. switch (type) {
  100. case 15:
  101. return '按照如下格式输入:APIKey|SecretKey';
  102. case 18:
  103. return '按照如下格式输入:APPID|APISecret|APIKey';
  104. case 22:
  105. return '按照如下格式输入:APIKey-AppId,例如:fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041';
  106. case 23:
  107. return '按照如下格式输入:AppId|SecretId|SecretKey';
  108. case 33:
  109. return '按照如下格式输入:Ak|Sk|Region';
  110. case 50:
  111. return '按照如下格式输入: AccessKey|SecretKey, 如果上游是New API,则直接输ApiKey';
  112. case 51:
  113. return '按照如下格式输入: Access Key ID|Secret Access Key';
  114. default:
  115. return '请输入渠道对应的鉴权密钥';
  116. }
  117. }
  118. const EditChannelModal = (props) => {
  119. const { t } = useTranslation();
  120. const channelId = props.editingChannel.id;
  121. const isEdit = channelId !== undefined;
  122. const [loading, setLoading] = useState(isEdit);
  123. const isMobile = useIsMobile();
  124. const handleCancel = () => {
  125. props.handleClose();
  126. };
  127. const originInputs = {
  128. name: '',
  129. type: 1,
  130. key: '',
  131. openai_organization: '',
  132. max_input_tokens: 0,
  133. base_url: '',
  134. other: '',
  135. model_mapping: '',
  136. status_code_mapping: '',
  137. models: [],
  138. auto_ban: 1,
  139. test_model: '',
  140. groups: ['default'],
  141. priority: 0,
  142. weight: 0,
  143. tag: '',
  144. multi_key_mode: 'random',
  145. // 渠道额外设置的默认值
  146. force_format: false,
  147. thinking_to_content: false,
  148. proxy: '',
  149. pass_through_body_enabled: false,
  150. system_prompt: '',
  151. system_prompt_override: false,
  152. settings: '',
  153. // 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
  154. vertex_key_type: 'json',
  155. // 企业账户设置
  156. is_enterprise_account: false,
  157. };
  158. const [batch, setBatch] = useState(false);
  159. const [multiToSingle, setMultiToSingle] = useState(false);
  160. const [multiKeyMode, setMultiKeyMode] = useState('random');
  161. const [autoBan, setAutoBan] = useState(true);
  162. const [inputs, setInputs] = useState(originInputs);
  163. const [originModelOptions, setOriginModelOptions] = useState([]);
  164. const [modelOptions, setModelOptions] = useState([]);
  165. const [groupOptions, setGroupOptions] = useState([]);
  166. const [basicModels, setBasicModels] = useState([]);
  167. const [fullModels, setFullModels] = useState([]);
  168. const [modelGroups, setModelGroups] = useState([]);
  169. const [customModel, setCustomModel] = useState('');
  170. const [modalImageUrl, setModalImageUrl] = useState('');
  171. const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  172. const [modelModalVisible, setModelModalVisible] = useState(false);
  173. const [fetchedModels, setFetchedModels] = useState([]);
  174. const formApiRef = useRef(null);
  175. const [vertexKeys, setVertexKeys] = useState([]);
  176. const [vertexFileList, setVertexFileList] = useState([]);
  177. const vertexErroredNames = useRef(new Set()); // 避免重复报错
  178. const [isMultiKeyChannel, setIsMultiKeyChannel] = useState(false);
  179. const [channelSearchValue, setChannelSearchValue] = useState('');
  180. const [useManualInput, setUseManualInput] = useState(false); // 是否使用手动输入模式
  181. const [keyMode, setKeyMode] = useState('append'); // 密钥模式:replace(覆盖)或 append(追加)
  182. const [isEnterpriseAccount, setIsEnterpriseAccount] = useState(false); // 是否为企业账户
  183. // 2FA验证查看密钥相关状态
  184. const [twoFAState, setTwoFAState] = useState({
  185. showModal: false,
  186. code: '',
  187. loading: false,
  188. showKey: false,
  189. keyData: '',
  190. });
  191. // 专门的2FA验证状态(用于TwoFactorAuthModal)
  192. const [show2FAVerifyModal, setShow2FAVerifyModal] = useState(false);
  193. const [verifyCode, setVerifyCode] = useState('');
  194. const [verifyLoading, setVerifyLoading] = useState(false);
  195. // 2FA状态更新辅助函数
  196. const updateTwoFAState = (updates) => {
  197. setTwoFAState((prev) => ({ ...prev, ...updates }));
  198. };
  199. // 重置2FA状态
  200. const resetTwoFAState = () => {
  201. setTwoFAState({
  202. showModal: false,
  203. code: '',
  204. loading: false,
  205. showKey: false,
  206. keyData: '',
  207. });
  208. };
  209. // 重置2FA验证状态
  210. const reset2FAVerifyState = () => {
  211. setShow2FAVerifyModal(false);
  212. setVerifyCode('');
  213. setVerifyLoading(false);
  214. };
  215. // 渠道额外设置状态
  216. const [channelSettings, setChannelSettings] = useState({
  217. force_format: false,
  218. thinking_to_content: false,
  219. proxy: '',
  220. pass_through_body_enabled: false,
  221. system_prompt: '',
  222. });
  223. const showApiConfigCard = true; // 控制是否显示 API 配置卡片
  224. const getInitValues = () => ({ ...originInputs });
  225. // 处理渠道额外设置的更新
  226. const handleChannelSettingsChange = (key, value) => {
  227. // 更新内部状态
  228. setChannelSettings((prev) => ({ ...prev, [key]: value }));
  229. // 同步更新到表单字段
  230. if (formApiRef.current) {
  231. formApiRef.current.setValue(key, value);
  232. }
  233. // 同步更新inputs状态
  234. setInputs((prev) => ({ ...prev, [key]: value }));
  235. // 生成setting JSON并更新
  236. const newSettings = { ...channelSettings, [key]: value };
  237. const settingsJson = JSON.stringify(newSettings);
  238. handleInputChange('setting', settingsJson);
  239. };
  240. const handleChannelOtherSettingsChange = (key, value) => {
  241. // 更新内部状态
  242. setChannelSettings((prev) => ({ ...prev, [key]: value }));
  243. // 同步更新到表单字段
  244. if (formApiRef.current) {
  245. formApiRef.current.setValue(key, value);
  246. }
  247. // 同步更新inputs状态
  248. setInputs((prev) => ({ ...prev, [key]: value }));
  249. // 需要更新settings,是一个json,例如{"azure_responses_version": "preview"}
  250. let settings = {};
  251. if (inputs.settings) {
  252. try {
  253. settings = JSON.parse(inputs.settings);
  254. } catch (error) {
  255. console.error('解析设置失败:', error);
  256. }
  257. }
  258. settings[key] = value;
  259. const settingsJson = JSON.stringify(settings);
  260. handleInputChange('settings', settingsJson);
  261. };
  262. const handleInputChange = (name, value) => {
  263. if (formApiRef.current) {
  264. formApiRef.current.setValue(name, value);
  265. }
  266. if (name === 'models' && Array.isArray(value)) {
  267. value = Array.from(new Set(value.map((m) => (m || '').trim())));
  268. }
  269. if (name === 'base_url' && value.endsWith('/v1')) {
  270. Modal.confirm({
  271. title: '警告',
  272. content:
  273. '不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?',
  274. onOk: () => {
  275. setInputs((inputs) => ({ ...inputs, [name]: value }));
  276. },
  277. });
  278. return;
  279. }
  280. setInputs((inputs) => ({ ...inputs, [name]: value }));
  281. if (name === 'type') {
  282. let localModels = [];
  283. switch (value) {
  284. case 2:
  285. localModels = [
  286. 'mj_imagine',
  287. 'mj_variation',
  288. 'mj_reroll',
  289. 'mj_blend',
  290. 'mj_upscale',
  291. 'mj_describe',
  292. 'mj_uploads',
  293. ];
  294. break;
  295. case 5:
  296. localModels = [
  297. 'swap_face',
  298. 'mj_imagine',
  299. 'mj_video',
  300. 'mj_edits',
  301. 'mj_variation',
  302. 'mj_reroll',
  303. 'mj_blend',
  304. 'mj_upscale',
  305. 'mj_describe',
  306. 'mj_zoom',
  307. 'mj_shorten',
  308. 'mj_modal',
  309. 'mj_inpaint',
  310. 'mj_custom_zoom',
  311. 'mj_high_variation',
  312. 'mj_low_variation',
  313. 'mj_pan',
  314. 'mj_uploads',
  315. ];
  316. break;
  317. case 36:
  318. localModels = ['suno_music', 'suno_lyrics'];
  319. break;
  320. case 45:
  321. localModels = getChannelModels(value);
  322. setInputs((prevInputs) => ({ ...prevInputs, base_url: 'https://ark.cn-beijing.volces.com' }));
  323. break;
  324. default:
  325. localModels = getChannelModels(value);
  326. break;
  327. }
  328. if (inputs.models.length === 0) {
  329. setInputs((inputs) => ({ ...inputs, models: localModels }));
  330. }
  331. setBasicModels(localModels);
  332. // 重置手动输入模式状态
  333. setUseManualInput(false);
  334. }
  335. //setAutoBan
  336. };
  337. const loadChannel = async () => {
  338. setLoading(true);
  339. let res = await API.get(`/api/channel/${channelId}`);
  340. if (res === undefined) {
  341. return;
  342. }
  343. const { success, message, data } = res.data;
  344. if (success) {
  345. if (data.models === '') {
  346. data.models = [];
  347. } else {
  348. data.models = data.models.split(',');
  349. }
  350. if (data.group === '') {
  351. data.groups = [];
  352. } else {
  353. data.groups = data.group.split(',');
  354. }
  355. if (data.model_mapping !== '') {
  356. data.model_mapping = JSON.stringify(
  357. JSON.parse(data.model_mapping),
  358. null,
  359. 2,
  360. );
  361. }
  362. const chInfo = data.channel_info || {};
  363. const isMulti = chInfo.is_multi_key === true;
  364. setIsMultiKeyChannel(isMulti);
  365. if (isMulti) {
  366. setBatch(true);
  367. setMultiToSingle(true);
  368. const modeVal = chInfo.multi_key_mode || 'random';
  369. setMultiKeyMode(modeVal);
  370. data.multi_key_mode = modeVal;
  371. } else {
  372. setBatch(false);
  373. setMultiToSingle(false);
  374. }
  375. // 解析渠道额外设置并合并到data中
  376. if (data.setting) {
  377. try {
  378. const parsedSettings = JSON.parse(data.setting);
  379. data.force_format = parsedSettings.force_format || false;
  380. data.thinking_to_content =
  381. parsedSettings.thinking_to_content || false;
  382. data.proxy = parsedSettings.proxy || '';
  383. data.pass_through_body_enabled =
  384. parsedSettings.pass_through_body_enabled || false;
  385. data.system_prompt = parsedSettings.system_prompt || '';
  386. data.system_prompt_override =
  387. parsedSettings.system_prompt_override || false;
  388. } catch (error) {
  389. console.error('解析渠道设置失败:', error);
  390. data.force_format = false;
  391. data.thinking_to_content = false;
  392. data.proxy = '';
  393. data.pass_through_body_enabled = false;
  394. data.system_prompt = '';
  395. data.system_prompt_override = false;
  396. }
  397. } else {
  398. data.force_format = false;
  399. data.thinking_to_content = false;
  400. data.proxy = '';
  401. data.pass_through_body_enabled = false;
  402. data.system_prompt = '';
  403. data.system_prompt_override = false;
  404. }
  405. if (data.settings) {
  406. try {
  407. const parsedSettings = JSON.parse(data.settings);
  408. data.azure_responses_version =
  409. parsedSettings.azure_responses_version || '';
  410. // 读取 Vertex 密钥格式
  411. data.vertex_key_type = parsedSettings.vertex_key_type || 'json';
  412. // 读取企业账户设置
  413. data.is_enterprise_account = parsedSettings.openrouter_enterprise === true;
  414. } catch (error) {
  415. console.error('解析其他设置失败:', error);
  416. data.azure_responses_version = '';
  417. data.region = '';
  418. data.vertex_key_type = 'json';
  419. data.is_enterprise_account = false;
  420. }
  421. } else {
  422. // 兼容历史数据:老渠道没有 settings 时,默认按 json 展示
  423. data.vertex_key_type = 'json';
  424. data.is_enterprise_account = false;
  425. }
  426. setInputs(data);
  427. if (formApiRef.current) {
  428. formApiRef.current.setValues(data);
  429. }
  430. if (data.auto_ban === 0) {
  431. setAutoBan(false);
  432. } else {
  433. setAutoBan(true);
  434. }
  435. // 同步企业账户状态
  436. setIsEnterpriseAccount(data.is_enterprise_account || false);
  437. setBasicModels(getChannelModels(data.type));
  438. // 同步更新channelSettings状态显示
  439. setChannelSettings({
  440. force_format: data.force_format,
  441. thinking_to_content: data.thinking_to_content,
  442. proxy: data.proxy,
  443. pass_through_body_enabled: data.pass_through_body_enabled,
  444. system_prompt: data.system_prompt,
  445. system_prompt_override: data.system_prompt_override || false,
  446. });
  447. // console.log(data);
  448. } else {
  449. showError(message);
  450. }
  451. setLoading(false);
  452. };
  453. const fetchUpstreamModelList = async (name) => {
  454. // if (inputs['type'] !== 1) {
  455. // showError(t('仅支持 OpenAI 接口格式'));
  456. // return;
  457. // }
  458. setLoading(true);
  459. const models = [];
  460. let err = false;
  461. if (isEdit) {
  462. // 如果是编辑模式,使用已有的 channelId 获取模型列表
  463. const res = await API.get('/api/channel/fetch_models/' + channelId, {
  464. skipErrorHandler: true,
  465. });
  466. if (res && res.data && res.data.success) {
  467. models.push(...res.data.data);
  468. } else {
  469. err = true;
  470. }
  471. } else {
  472. // 如果是新建模式,通过后端代理获取模型列表
  473. if (!inputs?.['key']) {
  474. showError(t('请填写密钥'));
  475. err = true;
  476. } else {
  477. try {
  478. const res = await API.post(
  479. '/api/channel/fetch_models',
  480. {
  481. base_url: inputs['base_url'],
  482. type: inputs['type'],
  483. key: inputs['key'],
  484. },
  485. { skipErrorHandler: true },
  486. );
  487. if (res && res.data && res.data.success) {
  488. models.push(...res.data.data);
  489. } else {
  490. err = true;
  491. }
  492. } catch (error) {
  493. console.error('Error fetching models:', error);
  494. err = true;
  495. }
  496. }
  497. }
  498. if (!err) {
  499. const uniqueModels = Array.from(new Set(models));
  500. setFetchedModels(uniqueModels);
  501. setModelModalVisible(true);
  502. } else {
  503. showError(t('获取模型列表失败'));
  504. }
  505. setLoading(false);
  506. };
  507. const fetchModels = async () => {
  508. try {
  509. let res = await API.get(`/api/channel/models`);
  510. const localModelOptions = res.data.data.map((model) => {
  511. const id = (model.id || '').trim();
  512. return {
  513. key: id,
  514. label: id,
  515. value: id,
  516. };
  517. });
  518. setOriginModelOptions(localModelOptions);
  519. setFullModels(res.data.data.map((model) => model.id));
  520. setBasicModels(
  521. res.data.data
  522. .filter((model) => {
  523. return model.id.startsWith('gpt-') || model.id.startsWith('text-');
  524. })
  525. .map((model) => model.id),
  526. );
  527. } catch (error) {
  528. showError(error.message);
  529. }
  530. };
  531. const fetchGroups = async () => {
  532. try {
  533. let res = await API.get(`/api/group/`);
  534. if (res === undefined) {
  535. return;
  536. }
  537. setGroupOptions(
  538. res.data.data.map((group) => ({
  539. label: group,
  540. value: group,
  541. })),
  542. );
  543. } catch (error) {
  544. showError(error.message);
  545. }
  546. };
  547. const fetchModelGroups = async () => {
  548. try {
  549. const res = await API.get('/api/prefill_group?type=model');
  550. if (res?.data?.success) {
  551. setModelGroups(res.data.data || []);
  552. }
  553. } catch (error) {
  554. // ignore
  555. }
  556. };
  557. // 使用TwoFactorAuthModal的验证函数
  558. const handleVerify2FA = async () => {
  559. if (!verifyCode) {
  560. showError(t('请输入验证码或备用码'));
  561. return;
  562. }
  563. setVerifyLoading(true);
  564. try {
  565. const res = await API.post(`/api/channel/${channelId}/key`, {
  566. code: verifyCode,
  567. });
  568. if (res.data.success) {
  569. // 验证成功,显示密钥
  570. updateTwoFAState({
  571. showModal: true,
  572. showKey: true,
  573. keyData: res.data.data.key,
  574. });
  575. reset2FAVerifyState();
  576. showSuccess(t('验证成功'));
  577. } else {
  578. showError(res.data.message);
  579. }
  580. } catch (error) {
  581. showError(t('获取密钥失败'));
  582. } finally {
  583. setVerifyLoading(false);
  584. }
  585. };
  586. // 显示2FA验证模态框 - 使用TwoFactorAuthModal
  587. const handleShow2FAModal = () => {
  588. setShow2FAVerifyModal(true);
  589. };
  590. useEffect(() => {
  591. const modelMap = new Map();
  592. originModelOptions.forEach((option) => {
  593. const v = (option.value || '').trim();
  594. if (!modelMap.has(v)) {
  595. modelMap.set(v, option);
  596. }
  597. });
  598. inputs.models.forEach((model) => {
  599. const v = (model || '').trim();
  600. if (!modelMap.has(v)) {
  601. modelMap.set(v, {
  602. key: v,
  603. label: v,
  604. value: v,
  605. });
  606. }
  607. });
  608. const categories = getModelCategories(t);
  609. const optionsWithIcon = Array.from(modelMap.values()).map((opt) => {
  610. const modelName = opt.value;
  611. let icon = null;
  612. for (const [key, category] of Object.entries(categories)) {
  613. if (key !== 'all' && category.filter({ model_name: modelName })) {
  614. icon = category.icon;
  615. break;
  616. }
  617. }
  618. return {
  619. ...opt,
  620. label: (
  621. <span className='flex items-center gap-1'>
  622. {icon}
  623. {modelName}
  624. </span>
  625. ),
  626. };
  627. });
  628. setModelOptions(optionsWithIcon);
  629. }, [originModelOptions, inputs.models, t]);
  630. useEffect(() => {
  631. fetchModels().then();
  632. fetchGroups().then();
  633. if (!isEdit) {
  634. setInputs(originInputs);
  635. if (formApiRef.current) {
  636. formApiRef.current.setValues(originInputs);
  637. }
  638. let localModels = getChannelModels(inputs.type);
  639. setBasicModels(localModels);
  640. setInputs((inputs) => ({ ...inputs, models: localModels }));
  641. }
  642. }, [props.editingChannel.id]);
  643. useEffect(() => {
  644. if (formApiRef.current) {
  645. formApiRef.current.setValues(inputs);
  646. }
  647. }, [inputs]);
  648. useEffect(() => {
  649. if (props.visible) {
  650. if (isEdit) {
  651. loadChannel();
  652. } else {
  653. formApiRef.current?.setValues(getInitValues());
  654. }
  655. fetchModelGroups();
  656. // 重置手动输入模式状态
  657. setUseManualInput(false);
  658. } else {
  659. // 统一的模态框关闭重置逻辑
  660. resetModalState();
  661. }
  662. }, [props.visible, channelId]);
  663. // 统一的模态框重置函数
  664. const resetModalState = () => {
  665. formApiRef.current?.reset();
  666. // 重置渠道设置状态
  667. setChannelSettings({
  668. force_format: false,
  669. thinking_to_content: false,
  670. proxy: '',
  671. pass_through_body_enabled: false,
  672. system_prompt: '',
  673. system_prompt_override: false,
  674. });
  675. // 重置密钥模式状态
  676. setKeyMode('append');
  677. // 重置企业账户状态
  678. setIsEnterpriseAccount(false);
  679. // 清空表单中的key_mode字段
  680. if (formApiRef.current) {
  681. formApiRef.current.setValue('key_mode', undefined);
  682. }
  683. // 重置本地输入,避免下次打开残留上一次的 JSON 字段值
  684. setInputs(getInitValues());
  685. // 重置2FA状态
  686. resetTwoFAState();
  687. // 重置2FA验证状态
  688. reset2FAVerifyState();
  689. };
  690. const handleVertexUploadChange = ({ fileList }) => {
  691. vertexErroredNames.current.clear();
  692. (async () => {
  693. let validFiles = [];
  694. let keys = [];
  695. const errorNames = [];
  696. for (const item of fileList) {
  697. const fileObj = item.fileInstance;
  698. if (!fileObj) continue;
  699. try {
  700. const txt = await fileObj.text();
  701. keys.push(JSON.parse(txt));
  702. validFiles.push(item);
  703. } catch (err) {
  704. if (!vertexErroredNames.current.has(item.name)) {
  705. errorNames.push(item.name);
  706. vertexErroredNames.current.add(item.name);
  707. }
  708. }
  709. }
  710. // 非批量模式下只保留一个文件(最新选择的),避免重复叠加
  711. if (!batch && validFiles.length > 1) {
  712. validFiles = [validFiles[validFiles.length - 1]];
  713. keys = [keys[keys.length - 1]];
  714. }
  715. setVertexKeys(keys);
  716. setVertexFileList(validFiles);
  717. if (formApiRef.current) {
  718. formApiRef.current.setValue('vertex_files', validFiles);
  719. }
  720. setInputs((prev) => ({ ...prev, vertex_files: validFiles }));
  721. if (errorNames.length > 0) {
  722. showError(
  723. t('以下文件解析失败,已忽略:{{list}}', {
  724. list: errorNames.join(', '),
  725. }),
  726. );
  727. }
  728. })();
  729. };
  730. const submit = async () => {
  731. const formValues = formApiRef.current ? formApiRef.current.getValues() : {};
  732. let localInputs = { ...formValues };
  733. if (localInputs.type === 41) {
  734. const keyType = localInputs.vertex_key_type || 'json';
  735. if (keyType === 'api_key') {
  736. // 直接作为普通字符串密钥处理
  737. if (!isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
  738. showInfo(t('请输入密钥!'));
  739. return;
  740. }
  741. } else {
  742. // JSON 服务账号密钥
  743. if (useManualInput) {
  744. if (localInputs.key && localInputs.key.trim() !== '') {
  745. try {
  746. const parsedKey = JSON.parse(localInputs.key);
  747. localInputs.key = JSON.stringify(parsedKey);
  748. } catch (err) {
  749. showError(t('密钥格式无效,请输入有效的 JSON 格式密钥'));
  750. return;
  751. }
  752. } else if (!isEdit) {
  753. showInfo(t('请输入密钥!'));
  754. return;
  755. }
  756. } else {
  757. // 文件上传模式
  758. let keys = vertexKeys;
  759. if (keys.length === 0 && vertexFileList.length > 0) {
  760. try {
  761. const parsed = await Promise.all(
  762. vertexFileList.map(async (item) => {
  763. const fileObj = item.fileInstance;
  764. if (!fileObj) return null;
  765. const txt = await fileObj.text();
  766. return JSON.parse(txt);
  767. }),
  768. );
  769. keys = parsed.filter(Boolean);
  770. } catch (err) {
  771. showError(t('解析密钥文件失败: {{msg}}', { msg: err.message }));
  772. return;
  773. }
  774. }
  775. if (keys.length === 0) {
  776. if (!isEdit) {
  777. showInfo(t('请上传密钥文件!'));
  778. return;
  779. } else {
  780. delete localInputs.key;
  781. }
  782. } else {
  783. localInputs.key = batch ? JSON.stringify(keys) : JSON.stringify(keys[0]);
  784. }
  785. }
  786. }
  787. }
  788. // 如果是编辑模式且 key 为空字符串,避免提交空值覆盖旧密钥
  789. if (isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
  790. delete localInputs.key;
  791. }
  792. delete localInputs.vertex_files;
  793. if (!isEdit && (!localInputs.name || !localInputs.key)) {
  794. showInfo(t('请填写渠道名称和渠道密钥!'));
  795. return;
  796. }
  797. if (!Array.isArray(localInputs.models) || localInputs.models.length === 0) {
  798. showInfo(t('请至少选择一个模型!'));
  799. return;
  800. }
  801. if (localInputs.type === 45 && (!localInputs.base_url || localInputs.base_url.trim() === '')) {
  802. showInfo(t('请输入API地址!'));
  803. return;
  804. }
  805. if (
  806. localInputs.model_mapping &&
  807. localInputs.model_mapping !== '' &&
  808. !verifyJSON(localInputs.model_mapping)
  809. ) {
  810. showInfo(t('模型映射必须是合法的 JSON 格式!'));
  811. return;
  812. }
  813. if (localInputs.base_url && localInputs.base_url.endsWith('/')) {
  814. localInputs.base_url = localInputs.base_url.slice(
  815. 0,
  816. localInputs.base_url.length - 1,
  817. );
  818. }
  819. if (localInputs.type === 18 && localInputs.other === '') {
  820. localInputs.other = 'v2.1';
  821. }
  822. // 生成渠道额外设置JSON
  823. const channelExtraSettings = {
  824. force_format: localInputs.force_format || false,
  825. thinking_to_content: localInputs.thinking_to_content || false,
  826. proxy: localInputs.proxy || '',
  827. pass_through_body_enabled: localInputs.pass_through_body_enabled || false,
  828. system_prompt: localInputs.system_prompt || '',
  829. system_prompt_override: localInputs.system_prompt_override || false,
  830. };
  831. localInputs.setting = JSON.stringify(channelExtraSettings);
  832. // 处理type === 20的企业账户设置
  833. if (localInputs.type === 20) {
  834. let settings = {};
  835. if (localInputs.settings) {
  836. try {
  837. settings = JSON.parse(localInputs.settings);
  838. } catch (error) {
  839. console.error('解析settings失败:', error);
  840. }
  841. }
  842. // 设置企业账户标识,无论是true还是false都要传到后端
  843. settings.openrouter_enterprise = localInputs.is_enterprise_account === true;
  844. localInputs.settings = JSON.stringify(settings);
  845. }
  846. // 清理不需要发送到后端的字段
  847. delete localInputs.force_format;
  848. delete localInputs.thinking_to_content;
  849. delete localInputs.proxy;
  850. delete localInputs.pass_through_body_enabled;
  851. delete localInputs.system_prompt;
  852. delete localInputs.system_prompt_override;
  853. delete localInputs.is_enterprise_account;
  854. // 顶层的 vertex_key_type 不应发送给后端
  855. delete localInputs.vertex_key_type;
  856. let res;
  857. localInputs.auto_ban = localInputs.auto_ban ? 1 : 0;
  858. localInputs.models = localInputs.models.join(',');
  859. localInputs.group = (localInputs.groups || []).join(',');
  860. let mode = 'single';
  861. if (batch) {
  862. mode = multiToSingle ? 'multi_to_single' : 'batch';
  863. }
  864. if (isEdit) {
  865. res = await API.put(`/api/channel/`, {
  866. ...localInputs,
  867. id: parseInt(channelId),
  868. key_mode: isMultiKeyChannel ? keyMode : undefined, // 只在多key模式下传递
  869. });
  870. } else {
  871. res = await API.post(`/api/channel/`, {
  872. mode: mode,
  873. multi_key_mode: mode === 'multi_to_single' ? multiKeyMode : undefined,
  874. channel: localInputs,
  875. });
  876. }
  877. const { success, message } = res.data;
  878. if (success) {
  879. if (isEdit) {
  880. showSuccess(t('渠道更新成功!'));
  881. } else {
  882. showSuccess(t('渠道创建成功!'));
  883. setInputs(originInputs);
  884. }
  885. props.refresh();
  886. props.handleClose();
  887. } else {
  888. showError(message);
  889. }
  890. };
  891. const addCustomModels = () => {
  892. if (customModel.trim() === '') return;
  893. const modelArray = customModel.split(',').map((model) => model.trim());
  894. let localModels = [...inputs.models];
  895. let localModelOptions = [...modelOptions];
  896. const addedModels = [];
  897. modelArray.forEach((model) => {
  898. if (model && !localModels.includes(model)) {
  899. localModels.push(model);
  900. localModelOptions.push({
  901. key: model,
  902. label: model,
  903. value: model,
  904. });
  905. addedModels.push(model);
  906. }
  907. });
  908. setModelOptions(localModelOptions);
  909. setCustomModel('');
  910. handleInputChange('models', localModels);
  911. if (addedModels.length > 0) {
  912. showSuccess(
  913. t('已新增 {{count}} 个模型:{{list}}', {
  914. count: addedModels.length,
  915. list: addedModels.join(', '),
  916. }),
  917. );
  918. } else {
  919. showInfo(t('未发现新增模型'));
  920. }
  921. };
  922. const batchAllowed = !isEdit || isMultiKeyChannel;
  923. const batchExtra = batchAllowed ? (
  924. <Space>
  925. {!isEdit && (
  926. <Checkbox
  927. disabled={isEdit}
  928. checked={batch}
  929. onChange={(e) => {
  930. const checked = e.target.checked;
  931. if (!checked && vertexFileList.length > 1) {
  932. Modal.confirm({
  933. title: t('切换为单密钥模式'),
  934. content: t(
  935. '将仅保留第一个密钥文件,其余文件将被移除,是否继续?',
  936. ),
  937. onOk: () => {
  938. const firstFile = vertexFileList[0];
  939. const firstKey = vertexKeys[0] ? [vertexKeys[0]] : [];
  940. setVertexFileList([firstFile]);
  941. setVertexKeys(firstKey);
  942. formApiRef.current?.setValue('vertex_files', [firstFile]);
  943. setInputs((prev) => ({ ...prev, vertex_files: [firstFile] }));
  944. setBatch(false);
  945. setMultiToSingle(false);
  946. setMultiKeyMode('random');
  947. },
  948. onCancel: () => {
  949. setBatch(true);
  950. },
  951. centered: true,
  952. });
  953. return;
  954. }
  955. setBatch(checked);
  956. if (!checked) {
  957. setMultiToSingle(false);
  958. setMultiKeyMode('random');
  959. } else {
  960. // 批量模式下禁用手动输入,并清空手动输入的内容
  961. setUseManualInput(false);
  962. if (inputs.type === 41) {
  963. // 清空手动输入的密钥内容
  964. if (formApiRef.current) {
  965. formApiRef.current.setValue('key', '');
  966. }
  967. handleInputChange('key', '');
  968. }
  969. }
  970. }}
  971. >
  972. {t('批量创建')}
  973. </Checkbox>
  974. )}
  975. {batch && (
  976. <Checkbox
  977. disabled={isEdit}
  978. checked={multiToSingle}
  979. onChange={() => {
  980. setMultiToSingle((prev) => !prev);
  981. setInputs((prev) => {
  982. const newInputs = { ...prev };
  983. if (!multiToSingle) {
  984. newInputs.multi_key_mode = multiKeyMode;
  985. } else {
  986. delete newInputs.multi_key_mode;
  987. }
  988. return newInputs;
  989. });
  990. }}
  991. >
  992. {t('密钥聚合模式')}
  993. </Checkbox>
  994. )}
  995. </Space>
  996. ) : null;
  997. const channelOptionList = useMemo(
  998. () =>
  999. CHANNEL_OPTIONS.map((opt) => ({
  1000. ...opt,
  1001. // 保持 label 为纯文本以支持搜索
  1002. label: opt.label,
  1003. })),
  1004. [],
  1005. );
  1006. const renderChannelOption = (renderProps) => {
  1007. const {
  1008. disabled,
  1009. selected,
  1010. label,
  1011. value,
  1012. focused,
  1013. className,
  1014. style,
  1015. onMouseEnter,
  1016. onClick,
  1017. ...rest
  1018. } = renderProps;
  1019. const searchWords = channelSearchValue ? [channelSearchValue] : [];
  1020. // 构建样式类名
  1021. const optionClassName = [
  1022. 'flex items-center gap-3 px-3 py-2 transition-all duration-200 rounded-lg mx-2 my-1',
  1023. focused && 'bg-blue-50 shadow-sm',
  1024. selected &&
  1025. 'bg-blue-100 text-blue-700 shadow-lg ring-2 ring-blue-200 ring-opacity-50',
  1026. disabled && 'opacity-50 cursor-not-allowed',
  1027. !disabled && 'hover:bg-gray-50 hover:shadow-md cursor-pointer',
  1028. className,
  1029. ]
  1030. .filter(Boolean)
  1031. .join(' ');
  1032. return (
  1033. <div
  1034. style={style}
  1035. className={optionClassName}
  1036. onClick={() => !disabled && onClick()}
  1037. onMouseEnter={(e) => onMouseEnter()}
  1038. >
  1039. <div className='flex items-center gap-3 w-full'>
  1040. <div className='flex-shrink-0 w-5 h-5 flex items-center justify-center'>
  1041. {getChannelIcon(value)}
  1042. </div>
  1043. <div className='flex-1 min-w-0'>
  1044. <Highlight
  1045. sourceString={label}
  1046. searchWords={searchWords}
  1047. className='text-sm font-medium truncate'
  1048. />
  1049. </div>
  1050. {selected && (
  1051. <div className='flex-shrink-0 text-blue-600'>
  1052. <svg
  1053. width='16'
  1054. height='16'
  1055. viewBox='0 0 16 16'
  1056. fill='currentColor'
  1057. >
  1058. <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' />
  1059. </svg>
  1060. </div>
  1061. )}
  1062. </div>
  1063. </div>
  1064. );
  1065. };
  1066. return (
  1067. <>
  1068. <SideSheet
  1069. placement={isEdit ? 'right' : 'left'}
  1070. title={
  1071. <Space>
  1072. <Tag color='blue' shape='circle'>
  1073. {isEdit ? t('编辑') : t('新建')}
  1074. </Tag>
  1075. <Title heading={4} className='m-0'>
  1076. {isEdit ? t('更新渠道信息') : t('创建新的渠道')}
  1077. </Title>
  1078. </Space>
  1079. }
  1080. bodyStyle={{ padding: '0' }}
  1081. visible={props.visible}
  1082. width={isMobile ? '100%' : 600}
  1083. footer={
  1084. <div className='flex justify-end bg-white'>
  1085. <Space>
  1086. <Button
  1087. theme='solid'
  1088. onClick={() => formApiRef.current?.submitForm()}
  1089. icon={<IconSave />}
  1090. >
  1091. {t('提交')}
  1092. </Button>
  1093. <Button
  1094. theme='light'
  1095. type='primary'
  1096. onClick={handleCancel}
  1097. icon={<IconClose />}
  1098. >
  1099. {t('取消')}
  1100. </Button>
  1101. </Space>
  1102. </div>
  1103. }
  1104. closeIcon={null}
  1105. onCancel={() => handleCancel()}
  1106. >
  1107. <Form
  1108. key={isEdit ? 'edit' : 'new'}
  1109. initValues={originInputs}
  1110. getFormApi={(api) => (formApiRef.current = api)}
  1111. onSubmit={submit}
  1112. >
  1113. {() => (
  1114. <Spin spinning={loading}>
  1115. <div className='p-2'>
  1116. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  1117. {/* Header: Basic Info */}
  1118. <div className='flex items-center mb-2'>
  1119. <Avatar
  1120. size='small'
  1121. color='blue'
  1122. className='mr-2 shadow-md'
  1123. >
  1124. <IconServer size={16} />
  1125. </Avatar>
  1126. <div>
  1127. <Text className='text-lg font-medium'>
  1128. {t('基本信息')}
  1129. </Text>
  1130. <div className='text-xs text-gray-600'>
  1131. {t('渠道的基本配置信息')}
  1132. </div>
  1133. </div>
  1134. </div>
  1135. <Form.Select
  1136. field='type'
  1137. label={t('类型')}
  1138. placeholder={t('请选择渠道类型')}
  1139. rules={[{ required: true, message: t('请选择渠道类型') }]}
  1140. optionList={channelOptionList}
  1141. style={{ width: '100%' }}
  1142. filter={selectFilter}
  1143. autoClearSearchValue={false}
  1144. searchPosition='dropdown'
  1145. onSearch={(value) => setChannelSearchValue(value)}
  1146. renderOptionItem={renderChannelOption}
  1147. onChange={(value) => handleInputChange('type', value)}
  1148. />
  1149. {inputs.type === 20 && (
  1150. <Form.Switch
  1151. field='is_enterprise_account'
  1152. label={t('是否为企业账户')}
  1153. checkedText={t('是')}
  1154. uncheckedText={t('否')}
  1155. onChange={(value) => {
  1156. setIsEnterpriseAccount(value);
  1157. handleInputChange('is_enterprise_account', value);
  1158. }}
  1159. extraText={t('企业账户为特殊返回格式,需要特殊处理,如果非企业账户,请勿勾选')}
  1160. initValue={inputs.is_enterprise_account}
  1161. />
  1162. )}
  1163. <Form.Input
  1164. field='name'
  1165. label={t('名称')}
  1166. placeholder={t('请为渠道命名')}
  1167. rules={[{ required: true, message: t('请为渠道命名') }]}
  1168. showClear
  1169. onChange={(value) => handleInputChange('name', value)}
  1170. autoComplete='new-password'
  1171. />
  1172. {inputs.type === 41 && (
  1173. <Form.Select
  1174. field='vertex_key_type'
  1175. label={t('密钥格式')}
  1176. placeholder={t('请选择密钥格式')}
  1177. optionList={[
  1178. { label: 'JSON', value: 'json' },
  1179. { label: 'API Key', value: 'api_key' },
  1180. ]}
  1181. style={{ width: '100%' }}
  1182. value={inputs.vertex_key_type || 'json'}
  1183. onChange={(value) => {
  1184. // 更新设置中的 vertex_key_type
  1185. handleChannelOtherSettingsChange('vertex_key_type', value);
  1186. // 切换为 api_key 时,关闭批量与手动/文件切换,并清理已选文件
  1187. if (value === 'api_key') {
  1188. setBatch(false);
  1189. setUseManualInput(false);
  1190. setVertexKeys([]);
  1191. setVertexFileList([]);
  1192. if (formApiRef.current) {
  1193. formApiRef.current.setValue('vertex_files', []);
  1194. }
  1195. }
  1196. }}
  1197. extraText={
  1198. inputs.vertex_key_type === 'api_key'
  1199. ? t('API Key 模式下不支持批量创建')
  1200. : t('JSON 模式支持手动输入或上传服务账号 JSON')
  1201. }
  1202. />
  1203. )}
  1204. {batch ? (
  1205. inputs.type === 41 && (inputs.vertex_key_type || 'json') === 'json' ? (
  1206. <Form.Upload
  1207. field='vertex_files'
  1208. label={t('密钥文件 (.json)')}
  1209. accept='.json'
  1210. multiple
  1211. draggable
  1212. dragIcon={<IconBolt />}
  1213. dragMainText={t('点击上传文件或拖拽文件到这里')}
  1214. dragSubText={t('仅支持 JSON 文件,支持多文件')}
  1215. style={{ marginTop: 10 }}
  1216. uploadTrigger='custom'
  1217. beforeUpload={() => false}
  1218. onChange={handleVertexUploadChange}
  1219. fileList={vertexFileList}
  1220. rules={
  1221. isEdit
  1222. ? []
  1223. : [{ required: true, message: t('请上传密钥文件') }]
  1224. }
  1225. extraText={batchExtra}
  1226. />
  1227. ) : (
  1228. <Form.TextArea
  1229. field='key'
  1230. label={t('密钥')}
  1231. placeholder={t('请输入密钥,一行一个')}
  1232. rules={
  1233. isEdit
  1234. ? []
  1235. : [{ required: true, message: t('请输入密钥') }]
  1236. }
  1237. autosize
  1238. autoComplete='new-password'
  1239. onChange={(value) => handleInputChange('key', value)}
  1240. extraText={
  1241. <div className='flex items-center gap-2'>
  1242. {isEdit &&
  1243. isMultiKeyChannel &&
  1244. keyMode === 'append' && (
  1245. <Text type='warning' size='small'>
  1246. {t(
  1247. '追加模式:新密钥将添加到现有密钥列表的末尾',
  1248. )}
  1249. </Text>
  1250. )}
  1251. {isEdit && (
  1252. <Button
  1253. size='small'
  1254. type='primary'
  1255. theme='outline'
  1256. onClick={handleShow2FAModal}
  1257. >
  1258. {t('查看密钥')}
  1259. </Button>
  1260. )}
  1261. {batchExtra}
  1262. </div>
  1263. }
  1264. showClear
  1265. />
  1266. )
  1267. ) : (
  1268. <>
  1269. {inputs.type === 41 && (inputs.vertex_key_type || 'json') === 'json' ? (
  1270. <>
  1271. {!batch && (
  1272. <div className='flex items-center justify-between mb-3'>
  1273. <Text className='text-sm font-medium'>
  1274. {t('密钥输入方式')}
  1275. </Text>
  1276. <Space>
  1277. <Button
  1278. size='small'
  1279. type={
  1280. !useManualInput ? 'primary' : 'tertiary'
  1281. }
  1282. onClick={() => {
  1283. setUseManualInput(false);
  1284. // 切换到文件上传模式时清空手动输入的密钥
  1285. if (formApiRef.current) {
  1286. formApiRef.current.setValue('key', '');
  1287. }
  1288. handleInputChange('key', '');
  1289. }}
  1290. >
  1291. {t('文件上传')}
  1292. </Button>
  1293. <Button
  1294. size='small'
  1295. type={useManualInput ? 'primary' : 'tertiary'}
  1296. onClick={() => {
  1297. setUseManualInput(true);
  1298. // 切换到手动输入模式时清空文件上传相关状态
  1299. setVertexKeys([]);
  1300. setVertexFileList([]);
  1301. if (formApiRef.current) {
  1302. formApiRef.current.setValue(
  1303. 'vertex_files',
  1304. [],
  1305. );
  1306. }
  1307. setInputs((prev) => ({
  1308. ...prev,
  1309. vertex_files: [],
  1310. }));
  1311. }}
  1312. >
  1313. {t('手动输入')}
  1314. </Button>
  1315. </Space>
  1316. </div>
  1317. )}
  1318. {batch && (
  1319. <Banner
  1320. type='info'
  1321. description={t(
  1322. '批量创建模式下仅支持文件上传,不支持手动输入',
  1323. )}
  1324. className='!rounded-lg mb-3'
  1325. />
  1326. )}
  1327. {useManualInput && !batch ? (
  1328. <Form.TextArea
  1329. field='key'
  1330. label={
  1331. isEdit
  1332. ? t('密钥(编辑模式下,保存的密钥不会显示)')
  1333. : t('密钥')
  1334. }
  1335. placeholder={t(
  1336. '请输入 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}',
  1337. )}
  1338. rules={
  1339. isEdit
  1340. ? []
  1341. : [
  1342. {
  1343. required: true,
  1344. message: t('请输入密钥'),
  1345. },
  1346. ]
  1347. }
  1348. autoComplete='new-password'
  1349. onChange={(value) =>
  1350. handleInputChange('key', value)
  1351. }
  1352. extraText={
  1353. <div className='flex items-center gap-2'>
  1354. <Text type='tertiary' size='small'>
  1355. {t('请输入完整的 JSON 格式密钥内容')}
  1356. </Text>
  1357. {isEdit &&
  1358. isMultiKeyChannel &&
  1359. keyMode === 'append' && (
  1360. <Text type='warning' size='small'>
  1361. {t(
  1362. '追加模式:新密钥将添加到现有密钥列表的末尾',
  1363. )}
  1364. </Text>
  1365. )}
  1366. {isEdit && (
  1367. <Button
  1368. size='small'
  1369. type='primary'
  1370. theme='outline'
  1371. onClick={handleShow2FAModal}
  1372. >
  1373. {t('查看密钥')}
  1374. </Button>
  1375. )}
  1376. {batchExtra}
  1377. </div>
  1378. }
  1379. autosize
  1380. showClear
  1381. />
  1382. ) : (
  1383. <Form.Upload
  1384. field='vertex_files'
  1385. label={t('密钥文件 (.json)')}
  1386. accept='.json'
  1387. draggable
  1388. dragIcon={<IconBolt />}
  1389. dragMainText={t('点击上传文件或拖拽文件到这里')}
  1390. dragSubText={t('仅支持 JSON 文件')}
  1391. style={{ marginTop: 10 }}
  1392. uploadTrigger='custom'
  1393. beforeUpload={() => false}
  1394. onChange={handleVertexUploadChange}
  1395. fileList={vertexFileList}
  1396. rules={
  1397. isEdit
  1398. ? []
  1399. : [
  1400. {
  1401. required: true,
  1402. message: t('请上传密钥文件'),
  1403. },
  1404. ]
  1405. }
  1406. extraText={batchExtra}
  1407. />
  1408. )}
  1409. </>
  1410. ) : (
  1411. <Form.Input
  1412. field='key'
  1413. label={
  1414. isEdit
  1415. ? t('密钥(编辑模式下,保存的密钥不会显示)')
  1416. : t('密钥')
  1417. }
  1418. placeholder={t(type2secretPrompt(inputs.type))}
  1419. rules={
  1420. isEdit
  1421. ? []
  1422. : [{ required: true, message: t('请输入密钥') }]
  1423. }
  1424. autoComplete='new-password'
  1425. onChange={(value) => handleInputChange('key', value)}
  1426. extraText={
  1427. <div className='flex items-center gap-2'>
  1428. {isEdit &&
  1429. isMultiKeyChannel &&
  1430. keyMode === 'append' && (
  1431. <Text type='warning' size='small'>
  1432. {t(
  1433. '追加模式:新密钥将添加到现有密钥列表的末尾',
  1434. )}
  1435. </Text>
  1436. )}
  1437. {isEdit && (
  1438. <Button
  1439. size='small'
  1440. type='primary'
  1441. theme='outline'
  1442. onClick={handleShow2FAModal}
  1443. >
  1444. {t('查看密钥')}
  1445. </Button>
  1446. )}
  1447. {batchExtra}
  1448. </div>
  1449. }
  1450. showClear
  1451. />
  1452. )}
  1453. </>
  1454. )}
  1455. {isEdit && isMultiKeyChannel && (
  1456. <Form.Select
  1457. field='key_mode'
  1458. label={t('密钥更新模式')}
  1459. placeholder={t('请选择密钥更新模式')}
  1460. optionList={[
  1461. { label: t('追加到现有密钥'), value: 'append' },
  1462. { label: t('覆盖现有密钥'), value: 'replace' },
  1463. ]}
  1464. style={{ width: '100%' }}
  1465. value={keyMode}
  1466. onChange={(value) => setKeyMode(value)}
  1467. extraText={
  1468. <Text type='tertiary' size='small'>
  1469. {keyMode === 'replace'
  1470. ? t('覆盖模式:将完全替换现有的所有密钥')
  1471. : t('追加模式:将新密钥添加到现有密钥列表末尾')}
  1472. </Text>
  1473. }
  1474. />
  1475. )}
  1476. {batch && multiToSingle && (
  1477. <>
  1478. <Form.Select
  1479. field='multi_key_mode'
  1480. label={t('密钥聚合模式')}
  1481. placeholder={t('请选择多密钥使用策略')}
  1482. optionList={[
  1483. { label: t('随机'), value: 'random' },
  1484. { label: t('轮询'), value: 'polling' },
  1485. ]}
  1486. style={{ width: '100%' }}
  1487. value={inputs.multi_key_mode || 'random'}
  1488. onChange={(value) => {
  1489. setMultiKeyMode(value);
  1490. handleInputChange('multi_key_mode', value);
  1491. }}
  1492. />
  1493. {inputs.multi_key_mode === 'polling' && (
  1494. <Banner
  1495. type='warning'
  1496. description={t(
  1497. '轮询模式必须搭配Redis和内存缓存功能使用,否则性能将大幅降低,并且无法实现轮询功能',
  1498. )}
  1499. className='!rounded-lg mt-2'
  1500. />
  1501. )}
  1502. </>
  1503. )}
  1504. {inputs.type === 18 && (
  1505. <Form.Input
  1506. field='other'
  1507. label={t('模型版本')}
  1508. placeholder={
  1509. '请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1'
  1510. }
  1511. onChange={(value) => handleInputChange('other', value)}
  1512. showClear
  1513. />
  1514. )}
  1515. {inputs.type === 41 && (
  1516. <JSONEditor
  1517. key={`region-${isEdit ? channelId : 'new'}`}
  1518. field='other'
  1519. label={t('部署地区')}
  1520. placeholder={t(
  1521. '请输入部署地区,例如:us-central1\n支持使用模型映射格式\n{\n "default": "us-central1",\n "claude-3-5-sonnet-20240620": "europe-west1"\n}',
  1522. )}
  1523. value={inputs.other || ''}
  1524. onChange={(value) => handleInputChange('other', value)}
  1525. rules={[{ required: true, message: t('请填写部署地区') }]}
  1526. template={REGION_EXAMPLE}
  1527. templateLabel={t('填入模板')}
  1528. editorType='region'
  1529. formApi={formApiRef.current}
  1530. extraText={t('设置默认地区和特定模型的专用地区')}
  1531. />
  1532. )}
  1533. {inputs.type === 21 && (
  1534. <Form.Input
  1535. field='other'
  1536. label={t('知识库 ID')}
  1537. placeholder={'请输入知识库 ID,例如:123456'}
  1538. onChange={(value) => handleInputChange('other', value)}
  1539. showClear
  1540. />
  1541. )}
  1542. {inputs.type === 39 && (
  1543. <Form.Input
  1544. field='other'
  1545. label='Account ID'
  1546. placeholder={
  1547. '请输入Account ID,例如:d6b5da8hk1awo8nap34ube6gh'
  1548. }
  1549. onChange={(value) => handleInputChange('other', value)}
  1550. showClear
  1551. />
  1552. )}
  1553. {inputs.type === 49 && (
  1554. <Form.Input
  1555. field='other'
  1556. label={t('智能体ID')}
  1557. placeholder={'请输入智能体ID,例如:7342866812345'}
  1558. onChange={(value) => handleInputChange('other', value)}
  1559. showClear
  1560. />
  1561. )}
  1562. {inputs.type === 1 && (
  1563. <Form.Input
  1564. field='openai_organization'
  1565. label={t('组织')}
  1566. placeholder={t('请输入组织org-xxx')}
  1567. showClear
  1568. helpText={t('组织,不填则为默认组织')}
  1569. onChange={(value) =>
  1570. handleInputChange('openai_organization', value)
  1571. }
  1572. />
  1573. )}
  1574. </Card>
  1575. {/* API Configuration Card */}
  1576. {showApiConfigCard && (
  1577. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  1578. {/* Header: API Config */}
  1579. <div className='flex items-center mb-2'>
  1580. <Avatar
  1581. size='small'
  1582. color='green'
  1583. className='mr-2 shadow-md'
  1584. >
  1585. <IconGlobe size={16} />
  1586. </Avatar>
  1587. <div>
  1588. <Text className='text-lg font-medium'>
  1589. {t('API 配置')}
  1590. </Text>
  1591. <div className='text-xs text-gray-600'>
  1592. {t('API 地址和相关配置')}
  1593. </div>
  1594. </div>
  1595. </div>
  1596. {inputs.type === 40 && (
  1597. <Banner
  1598. type='info'
  1599. description={
  1600. <div>
  1601. <Text strong>{t('邀请链接')}:</Text>
  1602. <Text
  1603. link
  1604. underline
  1605. className='ml-2 cursor-pointer'
  1606. onClick={() =>
  1607. window.open(
  1608. 'https://cloud.siliconflow.cn/i/hij0YNTZ',
  1609. )
  1610. }
  1611. >
  1612. https://cloud.siliconflow.cn/i/hij0YNTZ
  1613. </Text>
  1614. </div>
  1615. }
  1616. className='!rounded-lg'
  1617. />
  1618. )}
  1619. {inputs.type === 3 && (
  1620. <>
  1621. <Banner
  1622. type='warning'
  1623. description={t(
  1624. '2025年5月10日后添加的渠道,不需要再在部署的时候移除模型名称中的"."',
  1625. )}
  1626. className='!rounded-lg'
  1627. />
  1628. <div>
  1629. <Form.Input
  1630. field='base_url'
  1631. label='AZURE_OPENAI_ENDPOINT'
  1632. placeholder={t(
  1633. '请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com',
  1634. )}
  1635. onChange={(value) =>
  1636. handleInputChange('base_url', value)
  1637. }
  1638. showClear
  1639. />
  1640. </div>
  1641. <div>
  1642. <Form.Input
  1643. field='other'
  1644. label={t('默认 API 版本')}
  1645. placeholder={t(
  1646. '请输入默认 API 版本,例如:2025-04-01-preview',
  1647. )}
  1648. onChange={(value) =>
  1649. handleInputChange('other', value)
  1650. }
  1651. showClear
  1652. />
  1653. </div>
  1654. <div>
  1655. <Form.Input
  1656. field='azure_responses_version'
  1657. label={t(
  1658. '默认 Responses API 版本,为空则使用上方版本',
  1659. )}
  1660. placeholder={t('例如:preview')}
  1661. onChange={(value) =>
  1662. handleChannelOtherSettingsChange(
  1663. 'azure_responses_version',
  1664. value,
  1665. )
  1666. }
  1667. showClear
  1668. />
  1669. </div>
  1670. </>
  1671. )}
  1672. {inputs.type === 8 && (
  1673. <>
  1674. <Banner
  1675. type='warning'
  1676. description={t(
  1677. '如果你对接的是上游One API或者New API等转发项目,请使用OpenAI类型,不要使用此类型,除非你知道你在做什么。',
  1678. )}
  1679. className='!rounded-lg'
  1680. />
  1681. <div>
  1682. <Form.Input
  1683. field='base_url'
  1684. label={t('完整的 Base URL,支持变量{model}')}
  1685. placeholder={t(
  1686. '请输入完整的URL,例如:https://api.openai.com/v1/chat/completions',
  1687. )}
  1688. onChange={(value) =>
  1689. handleInputChange('base_url', value)
  1690. }
  1691. showClear
  1692. />
  1693. </div>
  1694. </>
  1695. )}
  1696. {inputs.type === 37 && (
  1697. <Banner
  1698. type='warning'
  1699. description={t(
  1700. 'Dify渠道只适配chatflow和agent,并且agent不支持图片!',
  1701. )}
  1702. className='!rounded-lg'
  1703. />
  1704. )}
  1705. {inputs.type !== 3 &&
  1706. inputs.type !== 8 &&
  1707. inputs.type !== 22 &&
  1708. inputs.type !== 36 &&
  1709. inputs.type !== 45 && (
  1710. <div>
  1711. <Form.Input
  1712. field='base_url'
  1713. label={t('API地址')}
  1714. placeholder={t(
  1715. '此项可选,用于通过自定义API地址来进行 API 调用,末尾不要带/v1和/',
  1716. )}
  1717. onChange={(value) =>
  1718. handleInputChange('base_url', value)
  1719. }
  1720. showClear
  1721. extraText={t(
  1722. '对于官方渠道,new-api已经内置地址,除非是第三方代理站点或者Azure的特殊接入地址,否则不需要填写',
  1723. )}
  1724. />
  1725. </div>
  1726. )}
  1727. {inputs.type === 22 && (
  1728. <div>
  1729. <Form.Input
  1730. field='base_url'
  1731. label={t('私有部署地址')}
  1732. placeholder={t(
  1733. '请输入私有部署地址,格式为:https://fastgpt.run/api/openapi',
  1734. )}
  1735. onChange={(value) =>
  1736. handleInputChange('base_url', value)
  1737. }
  1738. showClear
  1739. />
  1740. </div>
  1741. )}
  1742. {inputs.type === 36 && (
  1743. <div>
  1744. <Form.Input
  1745. field='base_url'
  1746. label={t(
  1747. '注意非Chat API,请务必填写正确的API地址,否则可能导致无法使用',
  1748. )}
  1749. placeholder={t(
  1750. '请输入到 /suno 前的路径,通常就是域名,例如:https://api.example.com',
  1751. )}
  1752. onChange={(value) =>
  1753. handleInputChange('base_url', value)
  1754. }
  1755. showClear
  1756. />
  1757. </div>
  1758. )}
  1759. {inputs.type === 45 && (
  1760. <div>
  1761. <Form.Select
  1762. field='base_url'
  1763. label={t('API地址')}
  1764. placeholder={t('请选择API地址')}
  1765. onChange={(value) =>
  1766. handleInputChange('base_url', value)
  1767. }
  1768. optionList={[
  1769. {
  1770. value: 'https://ark.cn-beijing.volces.com',
  1771. label: 'https://ark.cn-beijing.volces.com'
  1772. },
  1773. {
  1774. value: 'https://ark.ap-southeast.bytepluses.com',
  1775. label: 'https://ark.ap-southeast.bytepluses.com'
  1776. }
  1777. ]}
  1778. defaultValue='https://ark.cn-beijing.volces.com'
  1779. />
  1780. </div>
  1781. )}
  1782. </Card>
  1783. )}
  1784. {/* Model Configuration Card */}
  1785. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  1786. {/* Header: Model Config */}
  1787. <div className='flex items-center mb-2'>
  1788. <Avatar
  1789. size='small'
  1790. color='purple'
  1791. className='mr-2 shadow-md'
  1792. >
  1793. <IconCode size={16} />
  1794. </Avatar>
  1795. <div>
  1796. <Text className='text-lg font-medium'>
  1797. {t('模型配置')}
  1798. </Text>
  1799. <div className='text-xs text-gray-600'>
  1800. {t('模型选择和映射设置')}
  1801. </div>
  1802. </div>
  1803. </div>
  1804. <Form.Select
  1805. field='models'
  1806. label={t('模型')}
  1807. placeholder={t('请选择该渠道所支持的模型')}
  1808. rules={[{ required: true, message: t('请选择模型') }]}
  1809. multiple
  1810. filter={selectFilter}
  1811. autoClearSearchValue={false}
  1812. searchPosition='dropdown'
  1813. optionList={modelOptions}
  1814. style={{ width: '100%' }}
  1815. onChange={(value) => handleInputChange('models', value)}
  1816. renderSelectedItem={(optionNode) => {
  1817. const modelName = String(optionNode?.value ?? '');
  1818. return {
  1819. isRenderInTag: true,
  1820. content: (
  1821. <span
  1822. className='cursor-pointer select-none'
  1823. role='button'
  1824. tabIndex={0}
  1825. title={t('点击复制模型名称')}
  1826. onClick={async (e) => {
  1827. e.stopPropagation();
  1828. const ok = await copy(modelName);
  1829. if (ok) {
  1830. showSuccess(
  1831. t('已复制:{{name}}', { name: modelName }),
  1832. );
  1833. } else {
  1834. showError(t('复制失败'));
  1835. }
  1836. }}
  1837. >
  1838. {optionNode.label || modelName}
  1839. </span>
  1840. ),
  1841. };
  1842. }}
  1843. extraText={
  1844. <Space wrap>
  1845. <Button
  1846. size='small'
  1847. type='primary'
  1848. onClick={() =>
  1849. handleInputChange('models', basicModels)
  1850. }
  1851. >
  1852. {t('填入相关模型')}
  1853. </Button>
  1854. <Button
  1855. size='small'
  1856. type='secondary'
  1857. onClick={() =>
  1858. handleInputChange('models', fullModels)
  1859. }
  1860. >
  1861. {t('填入所有模型')}
  1862. </Button>
  1863. {MODEL_FETCHABLE_TYPES.has(inputs.type) && (
  1864. <Button
  1865. size='small'
  1866. type='tertiary'
  1867. onClick={() => fetchUpstreamModelList('models')}
  1868. >
  1869. {t('获取模型列表')}
  1870. </Button>
  1871. )}
  1872. <Button
  1873. size='small'
  1874. type='warning'
  1875. onClick={() => handleInputChange('models', [])}
  1876. >
  1877. {t('清除所有模型')}
  1878. </Button>
  1879. <Button
  1880. size='small'
  1881. type='tertiary'
  1882. onClick={() => {
  1883. if (inputs.models.length === 0) {
  1884. showInfo(t('没有模型可以复制'));
  1885. return;
  1886. }
  1887. try {
  1888. copy(inputs.models.join(','));
  1889. showSuccess(t('模型列表已复制到剪贴板'));
  1890. } catch (error) {
  1891. showError(t('复制失败'));
  1892. }
  1893. }}
  1894. >
  1895. {t('复制所有模型')}
  1896. </Button>
  1897. {modelGroups &&
  1898. modelGroups.length > 0 &&
  1899. modelGroups.map((group) => (
  1900. <Button
  1901. key={group.id}
  1902. size='small'
  1903. type='primary'
  1904. onClick={() => {
  1905. let items = [];
  1906. try {
  1907. if (Array.isArray(group.items)) {
  1908. items = group.items;
  1909. } else if (typeof group.items === 'string') {
  1910. const parsed = JSON.parse(
  1911. group.items || '[]',
  1912. );
  1913. if (Array.isArray(parsed)) items = parsed;
  1914. }
  1915. } catch {}
  1916. const current =
  1917. formApiRef.current?.getValue('models') ||
  1918. inputs.models ||
  1919. [];
  1920. const merged = Array.from(
  1921. new Set(
  1922. [...current, ...items]
  1923. .map((m) => (m || '').trim())
  1924. .filter(Boolean),
  1925. ),
  1926. );
  1927. handleInputChange('models', merged);
  1928. }}
  1929. >
  1930. {group.name}
  1931. </Button>
  1932. ))}
  1933. </Space>
  1934. }
  1935. />
  1936. <Form.Input
  1937. field='custom_model'
  1938. label={t('自定义模型名称')}
  1939. placeholder={t('输入自定义模型名称')}
  1940. onChange={(value) => setCustomModel(value.trim())}
  1941. value={customModel}
  1942. suffix={
  1943. <Button
  1944. size='small'
  1945. type='primary'
  1946. onClick={addCustomModels}
  1947. >
  1948. {t('填入')}
  1949. </Button>
  1950. }
  1951. />
  1952. <Form.Input
  1953. field='test_model'
  1954. label={t('默认测试模型')}
  1955. placeholder={t('不填则为模型列表第一个')}
  1956. onChange={(value) => handleInputChange('test_model', value)}
  1957. showClear
  1958. />
  1959. <JSONEditor
  1960. key={`model_mapping-${isEdit ? channelId : 'new'}`}
  1961. field='model_mapping'
  1962. label={t('模型重定向')}
  1963. placeholder={
  1964. t(
  1965. '此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:',
  1966. ) + `\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`
  1967. }
  1968. value={inputs.model_mapping || ''}
  1969. onChange={(value) =>
  1970. handleInputChange('model_mapping', value)
  1971. }
  1972. template={MODEL_MAPPING_EXAMPLE}
  1973. templateLabel={t('填入模板')}
  1974. editorType='keyValue'
  1975. formApi={formApiRef.current}
  1976. extraText={t('键为请求中的模型名称,值为要替换的模型名称')}
  1977. />
  1978. </Card>
  1979. {/* Advanced Settings Card */}
  1980. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  1981. {/* Header: Advanced Settings */}
  1982. <div className='flex items-center mb-2'>
  1983. <Avatar
  1984. size='small'
  1985. color='orange'
  1986. className='mr-2 shadow-md'
  1987. >
  1988. <IconSetting size={16} />
  1989. </Avatar>
  1990. <div>
  1991. <Text className='text-lg font-medium'>
  1992. {t('高级设置')}
  1993. </Text>
  1994. <div className='text-xs text-gray-600'>
  1995. {t('渠道的高级配置选项')}
  1996. </div>
  1997. </div>
  1998. </div>
  1999. <Form.Select
  2000. field='groups'
  2001. label={t('分组')}
  2002. placeholder={t('请选择可以使用该渠道的分组')}
  2003. multiple
  2004. allowAdditions
  2005. additionLabel={t(
  2006. '请在系统设置页面编辑分组倍率以添加新的分组:',
  2007. )}
  2008. optionList={groupOptions}
  2009. style={{ width: '100%' }}
  2010. onChange={(value) => handleInputChange('groups', value)}
  2011. />
  2012. <Form.Input
  2013. field='tag'
  2014. label={t('渠道标签')}
  2015. placeholder={t('渠道标签')}
  2016. showClear
  2017. onChange={(value) => handleInputChange('tag', value)}
  2018. />
  2019. <Form.TextArea
  2020. field='remark'
  2021. label={t('备注')}
  2022. placeholder={t('请输入备注(仅管理员可见)')}
  2023. maxLength={255}
  2024. showClear
  2025. onChange={(value) => handleInputChange('remark', value)}
  2026. />
  2027. <Row gutter={12}>
  2028. <Col span={12}>
  2029. <Form.InputNumber
  2030. field='priority'
  2031. label={t('渠道优先级')}
  2032. placeholder={t('渠道优先级')}
  2033. min={0}
  2034. onNumberChange={(value) =>
  2035. handleInputChange('priority', value)
  2036. }
  2037. style={{ width: '100%' }}
  2038. />
  2039. </Col>
  2040. <Col span={12}>
  2041. <Form.InputNumber
  2042. field='weight'
  2043. label={t('渠道权重')}
  2044. placeholder={t('渠道权重')}
  2045. min={0}
  2046. onNumberChange={(value) =>
  2047. handleInputChange('weight', value)
  2048. }
  2049. style={{ width: '100%' }}
  2050. />
  2051. </Col>
  2052. </Row>
  2053. <Form.Switch
  2054. field='auto_ban'
  2055. label={t('是否自动禁用')}
  2056. checkedText={t('开')}
  2057. uncheckedText={t('关')}
  2058. onChange={(value) => setAutoBan(value)}
  2059. extraText={t(
  2060. '仅当自动禁用开启时有效,关闭后不会自动禁用该渠道',
  2061. )}
  2062. initValue={autoBan}
  2063. />
  2064. <Form.TextArea
  2065. field='param_override'
  2066. label={t('参数覆盖')}
  2067. placeholder={
  2068. t('此项可选,用于覆盖请求参数。不支持覆盖 stream 参数') +
  2069. '\n' +
  2070. t('旧格式(直接覆盖):') +
  2071. '\n{\n "temperature": 0,\n "max_tokens": 1000\n}' +
  2072. '\n\n' +
  2073. t('新格式(支持条件判断与json自定义):') +
  2074. '\n{\n "operations": [\n {\n "path": "temperature",\n "mode": "set",\n "value": 0.7,\n "conditions": [\n {\n "path": "model",\n "mode": "prefix",\n "value": "gpt"\n }\n ]\n }\n ]\n}'
  2075. }
  2076. autosize
  2077. onChange={(value) =>
  2078. handleInputChange('param_override', value)
  2079. }
  2080. extraText={
  2081. <div className='flex gap-2 flex-wrap'>
  2082. <Text
  2083. className='!text-semi-color-primary cursor-pointer'
  2084. onClick={() =>
  2085. handleInputChange(
  2086. 'param_override',
  2087. JSON.stringify({ temperature: 0 }, null, 2),
  2088. )
  2089. }
  2090. >
  2091. {t('旧格式模板')}
  2092. </Text>
  2093. <Text
  2094. className='!text-semi-color-primary cursor-pointer'
  2095. onClick={() =>
  2096. handleInputChange(
  2097. 'param_override',
  2098. JSON.stringify(
  2099. {
  2100. operations: [
  2101. {
  2102. path: 'temperature',
  2103. mode: 'set',
  2104. value: 0.7,
  2105. conditions: [
  2106. {
  2107. path: 'model',
  2108. mode: 'prefix',
  2109. value: 'gpt',
  2110. },
  2111. ],
  2112. logic: 'AND',
  2113. },
  2114. ],
  2115. },
  2116. null,
  2117. 2,
  2118. ),
  2119. )
  2120. }
  2121. >
  2122. {t('新格式模板')}
  2123. </Text>
  2124. </div>
  2125. }
  2126. showClear
  2127. />
  2128. <Form.TextArea
  2129. field='header_override'
  2130. label={t('请求头覆盖')}
  2131. placeholder={
  2132. t('此项可选,用于覆盖请求头参数') +
  2133. '\n' +
  2134. t('格式示例:') +
  2135. '\n{\n "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0"\n}'
  2136. }
  2137. autosize
  2138. onChange={(value) =>
  2139. handleInputChange('header_override', value)
  2140. }
  2141. extraText={
  2142. <div className='flex gap-2 flex-wrap'>
  2143. <Text
  2144. className='!text-semi-color-primary cursor-pointer'
  2145. onClick={() =>
  2146. handleInputChange(
  2147. 'header_override',
  2148. JSON.stringify(
  2149. {
  2150. 'User-Agent':
  2151. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
  2152. },
  2153. null,
  2154. 2,
  2155. ),
  2156. )
  2157. }
  2158. >
  2159. {t('格式模板')}
  2160. </Text>
  2161. </div>
  2162. }
  2163. showClear
  2164. />
  2165. <JSONEditor
  2166. key={`status_code_mapping-${isEdit ? channelId : 'new'}`}
  2167. field='status_code_mapping'
  2168. label={t('状态码复写')}
  2169. placeholder={
  2170. t(
  2171. '此项可选,用于复写返回的状态码,仅影响本地判断,不修改返回到上游的状态码,比如将claude渠道的400错误复写为500(用于重试),请勿滥用该功能,例如:',
  2172. ) +
  2173. '\n' +
  2174. JSON.stringify(STATUS_CODE_MAPPING_EXAMPLE, null, 2)
  2175. }
  2176. value={inputs.status_code_mapping || ''}
  2177. onChange={(value) =>
  2178. handleInputChange('status_code_mapping', value)
  2179. }
  2180. template={STATUS_CODE_MAPPING_EXAMPLE}
  2181. templateLabel={t('填入模板')}
  2182. editorType='keyValue'
  2183. formApi={formApiRef.current}
  2184. extraText={t(
  2185. '键为原状态码,值为要复写的状态码,仅影响本地判断',
  2186. )}
  2187. />
  2188. </Card>
  2189. {/* Channel Extra Settings Card */}
  2190. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2191. {/* Header: Channel Extra Settings */}
  2192. <div className='flex items-center mb-2'>
  2193. <Avatar
  2194. size='small'
  2195. color='violet'
  2196. className='mr-2 shadow-md'
  2197. >
  2198. <IconBolt size={16} />
  2199. </Avatar>
  2200. <div>
  2201. <Text className='text-lg font-medium'>
  2202. {t('渠道额外设置')}
  2203. </Text>
  2204. </div>
  2205. </div>
  2206. {inputs.type === 1 && (
  2207. <Form.Switch
  2208. field='force_format'
  2209. label={t('强制格式化')}
  2210. checkedText={t('开')}
  2211. uncheckedText={t('关')}
  2212. onChange={(value) =>
  2213. handleChannelSettingsChange('force_format', value)
  2214. }
  2215. extraText={t(
  2216. '强制将响应格式化为 OpenAI 标准格式(只适用于OpenAI渠道类型)',
  2217. )}
  2218. />
  2219. )}
  2220. <Form.Switch
  2221. field='thinking_to_content'
  2222. label={t('思考内容转换')}
  2223. checkedText={t('开')}
  2224. uncheckedText={t('关')}
  2225. onChange={(value) =>
  2226. handleChannelSettingsChange('thinking_to_content', value)
  2227. }
  2228. extraText={t(
  2229. '将 reasoning_content 转换为 <think> 标签拼接到内容中',
  2230. )}
  2231. />
  2232. <Form.Switch
  2233. field='pass_through_body_enabled'
  2234. label={t('透传请求体')}
  2235. checkedText={t('开')}
  2236. uncheckedText={t('关')}
  2237. onChange={(value) =>
  2238. handleChannelSettingsChange(
  2239. 'pass_through_body_enabled',
  2240. value,
  2241. )
  2242. }
  2243. extraText={t('启用请求体透传功能')}
  2244. />
  2245. <Form.Input
  2246. field='proxy'
  2247. label={t('代理地址')}
  2248. placeholder={t('例如: socks5://user:pass@host:port')}
  2249. onChange={(value) =>
  2250. handleChannelSettingsChange('proxy', value)
  2251. }
  2252. showClear
  2253. extraText={t('用于配置网络代理,支持 socks5 协议')}
  2254. />
  2255. <Form.TextArea
  2256. field='system_prompt'
  2257. label={t('系统提示词')}
  2258. placeholder={t(
  2259. '输入系统提示词,用户的系统提示词将优先于此设置',
  2260. )}
  2261. onChange={(value) =>
  2262. handleChannelSettingsChange('system_prompt', value)
  2263. }
  2264. autosize
  2265. showClear
  2266. extraText={t(
  2267. '用户优先:如果用户在请求中指定了系统提示词,将优先使用用户的设置',
  2268. )}
  2269. />
  2270. <Form.Switch
  2271. field='system_prompt_override'
  2272. label={t('系统提示词拼接')}
  2273. checkedText={t('开')}
  2274. uncheckedText={t('关')}
  2275. onChange={(value) =>
  2276. handleChannelSettingsChange(
  2277. 'system_prompt_override',
  2278. value,
  2279. )
  2280. }
  2281. extraText={t(
  2282. '如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
  2283. )}
  2284. />
  2285. </Card>
  2286. </div>
  2287. </Spin>
  2288. )}
  2289. </Form>
  2290. <ImagePreview
  2291. src={modalImageUrl}
  2292. visible={isModalOpenurl}
  2293. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  2294. />
  2295. </SideSheet>
  2296. {/* 使用TwoFactorAuthModal组件进行2FA验证 */}
  2297. <TwoFactorAuthModal
  2298. visible={show2FAVerifyModal}
  2299. code={verifyCode}
  2300. loading={verifyLoading}
  2301. onCodeChange={setVerifyCode}
  2302. onVerify={handleVerify2FA}
  2303. onCancel={reset2FAVerifyState}
  2304. title={t('查看渠道密钥')}
  2305. description={t('为了保护账户安全,请验证您的两步验证码。')}
  2306. placeholder={t('请输入验证码或备用码')}
  2307. />
  2308. {/* 使用ChannelKeyDisplay组件显示密钥 */}
  2309. <Modal
  2310. title={
  2311. <div className='flex items-center'>
  2312. <div className='w-8 h-8 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center mr-3'>
  2313. <svg
  2314. className='w-4 h-4 text-green-600 dark:text-green-400'
  2315. fill='currentColor'
  2316. viewBox='0 0 20 20'
  2317. >
  2318. <path
  2319. fillRule='evenodd'
  2320. d='M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z'
  2321. clipRule='evenodd'
  2322. />
  2323. </svg>
  2324. </div>
  2325. {t('渠道密钥信息')}
  2326. </div>
  2327. }
  2328. visible={twoFAState.showModal && twoFAState.showKey}
  2329. onCancel={resetTwoFAState}
  2330. footer={
  2331. <Button type='primary' onClick={resetTwoFAState}>
  2332. {t('完成')}
  2333. </Button>
  2334. }
  2335. width={700}
  2336. style={{ maxWidth: '90vw' }}
  2337. >
  2338. <ChannelKeyDisplay
  2339. keyData={twoFAState.keyData}
  2340. showSuccessIcon={true}
  2341. successText={t('密钥获取成功')}
  2342. showWarning={true}
  2343. warningText={t(
  2344. '请妥善保管密钥信息,不要泄露给他人。如有安全疑虑,请及时更换密钥。',
  2345. )}
  2346. />
  2347. </Modal>
  2348. <ModelSelectModal
  2349. visible={modelModalVisible}
  2350. models={fetchedModels}
  2351. selected={inputs.models}
  2352. onConfirm={(selectedModels) => {
  2353. handleInputChange('models', selectedModels);
  2354. showSuccess(t('模型列表已更新'));
  2355. setModelModalVisible(false);
  2356. }}
  2357. onCancel={() => setModelModalVisible(false)}
  2358. />
  2359. </>
  2360. );
  2361. };
  2362. export default EditChannelModal;