EditChannelModal.jsx 87 KB

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