EditChannelModal.jsx 93 KB

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