EditChannelModal.jsx 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532
  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. Tooltip,
  45. } from '@douyinfe/semi-ui';
  46. import {
  47. getChannelModels,
  48. copy,
  49. getChannelIcon,
  50. getModelCategories,
  51. selectFilter,
  52. } from '../../../../helpers';
  53. import ModelSelectModal from './ModelSelectModal';
  54. import SingleModelSelectModal from './SingleModelSelectModal';
  55. import OllamaModelModal from './OllamaModelModal';
  56. import CodexOAuthModal from './CodexOAuthModal';
  57. import JSONEditor from '../../../common/ui/JSONEditor';
  58. import SecureVerificationModal from '../../../common/modals/SecureVerificationModal';
  59. import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay';
  60. import { useSecureVerification } from '../../../../hooks/common/useSecureVerification';
  61. import { createApiCalls } from '../../../../services/secureVerification';
  62. import {
  63. IconSave,
  64. IconClose,
  65. IconServer,
  66. IconSetting,
  67. IconCode,
  68. IconGlobe,
  69. IconBolt,
  70. IconSearch,
  71. IconChevronUp,
  72. IconChevronDown,
  73. } from '@douyinfe/semi-icons';
  74. const { Text, Title } = Typography;
  75. const MODEL_MAPPING_EXAMPLE = {
  76. 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
  77. };
  78. const STATUS_CODE_MAPPING_EXAMPLE = {
  79. 400: '500',
  80. };
  81. const REGION_EXAMPLE = {
  82. default: 'global',
  83. 'gemini-1.5-pro-002': 'europe-west2',
  84. 'gemini-1.5-flash-002': 'europe-west2',
  85. 'claude-3-5-sonnet-20240620': 'europe-west1',
  86. };
  87. // 支持并且已适配通过接口获取模型列表的渠道类型
  88. const MODEL_FETCHABLE_TYPES = new Set([
  89. 1, 4, 14, 34, 17, 26, 27, 24, 47, 25, 20, 23, 31, 40, 42, 48, 43,
  90. ]);
  91. function type2secretPrompt(type) {
  92. // inputs.type === 15 ? '按照如下格式输入:APIKey|SecretKey' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥')
  93. switch (type) {
  94. case 15:
  95. return '按照如下格式输入:APIKey|SecretKey';
  96. case 18:
  97. return '按照如下格式输入:APPID|APISecret|APIKey';
  98. case 22:
  99. return '按照如下格式输入:APIKey-AppId,例如:fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041';
  100. case 23:
  101. return '按照如下格式输入:AppId|SecretId|SecretKey';
  102. case 33:
  103. return '按照如下格式输入:Ak|Sk|Region';
  104. case 45:
  105. return '请输入渠道对应的鉴权密钥, 豆包语音输入:AppId|AccessToken';
  106. case 50:
  107. return '按照如下格式输入: AccessKey|SecretKey, 如果上游是New API,则直接输ApiKey';
  108. case 51:
  109. return '按照如下格式输入: AccessKey|SecretAccessKey';
  110. case 57:
  111. return '请输入 JSON 格式的 OAuth 凭据(必须包含 access_token 和 account_id)';
  112. default:
  113. return '请输入渠道对应的鉴权密钥';
  114. }
  115. }
  116. const EditChannelModal = (props) => {
  117. const { t } = useTranslation();
  118. const channelId = props.editingChannel.id;
  119. const isEdit = channelId !== undefined;
  120. const [loading, setLoading] = useState(isEdit);
  121. const isMobile = useIsMobile();
  122. const handleCancel = () => {
  123. props.handleClose();
  124. };
  125. const originInputs = {
  126. name: '',
  127. type: 1,
  128. key: '',
  129. openai_organization: '',
  130. max_input_tokens: 0,
  131. base_url: '',
  132. other: '',
  133. model_mapping: '',
  134. status_code_mapping: '',
  135. models: [],
  136. auto_ban: 1,
  137. test_model: '',
  138. groups: ['default'],
  139. priority: 0,
  140. weight: 0,
  141. tag: '',
  142. multi_key_mode: 'random',
  143. // 渠道额外设置的默认值
  144. force_format: false,
  145. thinking_to_content: false,
  146. proxy: '',
  147. pass_through_body_enabled: false,
  148. system_prompt: '',
  149. system_prompt_override: false,
  150. settings: '',
  151. // 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
  152. vertex_key_type: 'json',
  153. // 仅 AWS: 密钥格式和区域(存入 settings.aws_key_type 和 settings.aws_region)
  154. aws_key_type: 'ak_sk',
  155. // 企业账户设置
  156. is_enterprise_account: false,
  157. // 字段透传控制默认值
  158. allow_service_tier: false,
  159. disable_store: false, // false = 允许透传(默认开启)
  160. allow_safety_identifier: false,
  161. };
  162. const [batch, setBatch] = useState(false);
  163. const [multiToSingle, setMultiToSingle] = useState(false);
  164. const [multiKeyMode, setMultiKeyMode] = useState('random');
  165. const [autoBan, setAutoBan] = useState(true);
  166. const [inputs, setInputs] = useState(originInputs);
  167. const [originModelOptions, setOriginModelOptions] = useState([]);
  168. const [modelOptions, setModelOptions] = useState([]);
  169. const [groupOptions, setGroupOptions] = useState([]);
  170. const [basicModels, setBasicModels] = useState([]);
  171. const [fullModels, setFullModels] = useState([]);
  172. const [modelGroups, setModelGroups] = useState([]);
  173. const [customModel, setCustomModel] = useState('');
  174. const [modalImageUrl, setModalImageUrl] = useState('');
  175. const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  176. const [modelModalVisible, setModelModalVisible] = useState(false);
  177. const [fetchedModels, setFetchedModels] = useState([]);
  178. const [modelMappingValueModalVisible, setModelMappingValueModalVisible] =
  179. useState(false);
  180. const [modelMappingValueModalModels, setModelMappingValueModalModels] =
  181. useState([]);
  182. const [modelMappingValueKey, setModelMappingValueKey] = useState('');
  183. const [modelMappingValueSelected, setModelMappingValueSelected] =
  184. useState('');
  185. const [ollamaModalVisible, setOllamaModalVisible] = useState(false);
  186. const formApiRef = useRef(null);
  187. const [vertexKeys, setVertexKeys] = useState([]);
  188. const [vertexFileList, setVertexFileList] = useState([]);
  189. const vertexErroredNames = useRef(new Set()); // 避免重复报错
  190. const [isMultiKeyChannel, setIsMultiKeyChannel] = useState(false);
  191. const [channelSearchValue, setChannelSearchValue] = useState('');
  192. const [useManualInput, setUseManualInput] = useState(false); // 是否使用手动输入模式
  193. const [keyMode, setKeyMode] = useState('append'); // 密钥模式:replace(覆盖)或 append(追加)
  194. const [isEnterpriseAccount, setIsEnterpriseAccount] = useState(false); // 是否为企业账户
  195. const [doubaoApiEditUnlocked, setDoubaoApiEditUnlocked] = useState(false); // 豆包渠道自定义 API 地址隐藏入口
  196. const redirectModelList = useMemo(() => {
  197. const mapping = inputs.model_mapping;
  198. if (typeof mapping !== 'string') return [];
  199. const trimmed = mapping.trim();
  200. if (!trimmed) return [];
  201. try {
  202. const parsed = JSON.parse(trimmed);
  203. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
  204. return [];
  205. }
  206. const values = Object.values(parsed)
  207. .map((value) => (typeof value === 'string' ? value.trim() : undefined))
  208. .filter((value) => value);
  209. return Array.from(new Set(values));
  210. } catch (error) {
  211. return [];
  212. }
  213. }, [inputs.model_mapping]);
  214. const [isIonetChannel, setIsIonetChannel] = useState(false);
  215. const [ionetMetadata, setIonetMetadata] = useState(null);
  216. const [codexOAuthModalVisible, setCodexOAuthModalVisible] = useState(false);
  217. const [codexCredentialRefreshing, setCodexCredentialRefreshing] =
  218. useState(false);
  219. // 密钥显示状态
  220. const [keyDisplayState, setKeyDisplayState] = useState({
  221. showModal: false,
  222. keyData: '',
  223. });
  224. // 专门的2FA验证状态(用于TwoFactorAuthModal)
  225. const [show2FAVerifyModal, setShow2FAVerifyModal] = useState(false);
  226. const [verifyCode, setVerifyCode] = useState('');
  227. useEffect(() => {
  228. if (!isEdit) {
  229. setIsIonetChannel(false);
  230. setIonetMetadata(null);
  231. }
  232. }, [isEdit]);
  233. const handleOpenIonetDeployment = () => {
  234. if (!ionetMetadata?.deployment_id) {
  235. return;
  236. }
  237. const targetUrl = `/console/deployment?deployment_id=${ionetMetadata.deployment_id}`;
  238. window.open(targetUrl, '_blank', 'noopener');
  239. };
  240. const [verifyLoading, setVerifyLoading] = useState(false);
  241. // 表单块导航相关状态
  242. const formSectionRefs = useRef({
  243. basicInfo: null,
  244. apiConfig: null,
  245. modelConfig: null,
  246. advancedSettings: null,
  247. channelExtraSettings: null,
  248. });
  249. const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
  250. const formSections = [
  251. 'basicInfo',
  252. 'apiConfig',
  253. 'modelConfig',
  254. 'advancedSettings',
  255. 'channelExtraSettings',
  256. ];
  257. const formContainerRef = useRef(null);
  258. const doubaoApiClickCountRef = useRef(0);
  259. const initialModelsRef = useRef([]);
  260. const initialModelMappingRef = useRef('');
  261. // 2FA状态更新辅助函数
  262. const updateTwoFAState = (updates) => {
  263. setTwoFAState((prev) => ({ ...prev, ...updates }));
  264. };
  265. // 使用通用安全验证 Hook
  266. const {
  267. isModalVisible,
  268. verificationMethods,
  269. verificationState,
  270. withVerification,
  271. executeVerification,
  272. cancelVerification,
  273. setVerificationCode,
  274. switchVerificationMethod,
  275. } = useSecureVerification({
  276. onSuccess: (result) => {
  277. // 验证成功后显示密钥
  278. console.log('Verification success, result:', result);
  279. if (result && result.success && result.data?.key) {
  280. showSuccess(t('密钥获取成功'));
  281. setKeyDisplayState({
  282. showModal: true,
  283. keyData: result.data.key,
  284. });
  285. } else if (result && result.key) {
  286. // 直接返回了 key(没有包装在 data 中)
  287. showSuccess(t('密钥获取成功'));
  288. setKeyDisplayState({
  289. showModal: true,
  290. keyData: result.key,
  291. });
  292. }
  293. },
  294. });
  295. // 重置密钥显示状态
  296. const resetKeyDisplayState = () => {
  297. setKeyDisplayState({
  298. showModal: false,
  299. keyData: '',
  300. });
  301. };
  302. // 重置2FA验证状态
  303. const reset2FAVerifyState = () => {
  304. setShow2FAVerifyModal(false);
  305. setVerifyCode('');
  306. setVerifyLoading(false);
  307. };
  308. // 表单导航功能
  309. const scrollToSection = (sectionKey) => {
  310. const sectionElement = formSectionRefs.current[sectionKey];
  311. if (sectionElement) {
  312. sectionElement.scrollIntoView({
  313. behavior: 'smooth',
  314. block: 'start',
  315. inline: 'nearest',
  316. });
  317. }
  318. };
  319. const navigateToSection = (direction) => {
  320. const availableSections = formSections.filter((section) => {
  321. if (section === 'apiConfig') {
  322. return showApiConfigCard;
  323. }
  324. return true;
  325. });
  326. let newIndex;
  327. if (direction === 'up') {
  328. newIndex =
  329. currentSectionIndex > 0
  330. ? currentSectionIndex - 1
  331. : availableSections.length - 1;
  332. } else {
  333. newIndex =
  334. currentSectionIndex < availableSections.length - 1
  335. ? currentSectionIndex + 1
  336. : 0;
  337. }
  338. setCurrentSectionIndex(newIndex);
  339. scrollToSection(availableSections[newIndex]);
  340. };
  341. const handleApiConfigSecretClick = () => {
  342. if (inputs.type !== 45) return;
  343. const next = doubaoApiClickCountRef.current + 1;
  344. doubaoApiClickCountRef.current = next;
  345. if (next >= 10) {
  346. setDoubaoApiEditUnlocked((unlocked) => {
  347. if (!unlocked) {
  348. showInfo(t('已解锁豆包自定义 API 地址编辑'));
  349. }
  350. return true;
  351. });
  352. }
  353. };
  354. // 渠道额外设置状态
  355. const [channelSettings, setChannelSettings] = useState({
  356. force_format: false,
  357. thinking_to_content: false,
  358. proxy: '',
  359. pass_through_body_enabled: false,
  360. system_prompt: '',
  361. });
  362. const showApiConfigCard = true; // 控制是否显示 API 配置卡片
  363. const getInitValues = () => ({ ...originInputs });
  364. // 处理渠道额外设置的更新
  365. const handleChannelSettingsChange = (key, value) => {
  366. // 更新内部状态
  367. setChannelSettings((prev) => ({ ...prev, [key]: value }));
  368. // 同步更新到表单字段
  369. if (formApiRef.current) {
  370. formApiRef.current.setValue(key, value);
  371. }
  372. // 同步更新inputs状态
  373. setInputs((prev) => ({ ...prev, [key]: value }));
  374. // 生成setting JSON并更新
  375. const newSettings = { ...channelSettings, [key]: value };
  376. const settingsJson = JSON.stringify(newSettings);
  377. handleInputChange('setting', settingsJson);
  378. };
  379. const handleChannelOtherSettingsChange = (key, value) => {
  380. // 更新内部状态
  381. setChannelSettings((prev) => ({ ...prev, [key]: value }));
  382. // 同步更新到表单字段
  383. if (formApiRef.current) {
  384. formApiRef.current.setValue(key, value);
  385. }
  386. // 同步更新inputs状态
  387. setInputs((prev) => ({ ...prev, [key]: value }));
  388. // 需要更新settings,是一个json,例如{"azure_responses_version": "preview"}
  389. let settings = {};
  390. if (inputs.settings) {
  391. try {
  392. settings = JSON.parse(inputs.settings);
  393. } catch (error) {
  394. console.error('解析设置失败:', error);
  395. }
  396. }
  397. settings[key] = value;
  398. const settingsJson = JSON.stringify(settings);
  399. handleInputChange('settings', settingsJson);
  400. };
  401. const isIonetLocked = isIonetChannel && isEdit;
  402. const handleInputChange = (name, value) => {
  403. if (
  404. isIonetChannel &&
  405. isEdit &&
  406. ['type', 'key', 'base_url'].includes(name)
  407. ) {
  408. return;
  409. }
  410. if (formApiRef.current) {
  411. formApiRef.current.setValue(name, value);
  412. }
  413. if (name === 'models' && Array.isArray(value)) {
  414. value = Array.from(new Set(value.map((m) => (m || '').trim())));
  415. }
  416. if (name === 'base_url' && value.endsWith('/v1')) {
  417. Modal.confirm({
  418. title: '警告',
  419. content:
  420. '不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?',
  421. onOk: () => {
  422. setInputs((inputs) => ({ ...inputs, [name]: value }));
  423. },
  424. });
  425. return;
  426. }
  427. setInputs((inputs) => ({ ...inputs, [name]: value }));
  428. if (name === 'type') {
  429. let localModels = [];
  430. switch (value) {
  431. case 2:
  432. localModels = [
  433. 'mj_imagine',
  434. 'mj_variation',
  435. 'mj_reroll',
  436. 'mj_blend',
  437. 'mj_upscale',
  438. 'mj_describe',
  439. 'mj_uploads',
  440. ];
  441. break;
  442. case 5:
  443. localModels = [
  444. 'swap_face',
  445. 'mj_imagine',
  446. 'mj_video',
  447. 'mj_edits',
  448. 'mj_variation',
  449. 'mj_reroll',
  450. 'mj_blend',
  451. 'mj_upscale',
  452. 'mj_describe',
  453. 'mj_zoom',
  454. 'mj_shorten',
  455. 'mj_modal',
  456. 'mj_inpaint',
  457. 'mj_custom_zoom',
  458. 'mj_high_variation',
  459. 'mj_low_variation',
  460. 'mj_pan',
  461. 'mj_uploads',
  462. ];
  463. break;
  464. case 36:
  465. localModels = ['suno_music', 'suno_lyrics'];
  466. break;
  467. case 45:
  468. localModels = getChannelModels(value);
  469. setInputs((prevInputs) => ({
  470. ...prevInputs,
  471. base_url: 'https://ark.cn-beijing.volces.com',
  472. }));
  473. break;
  474. default:
  475. localModels = getChannelModels(value);
  476. break;
  477. }
  478. if (inputs.models.length === 0) {
  479. setInputs((inputs) => ({ ...inputs, models: localModels }));
  480. }
  481. setBasicModels(localModels);
  482. // 重置手动输入模式状态
  483. setUseManualInput(false);
  484. if (value === 57) {
  485. setBatch(false);
  486. setMultiToSingle(false);
  487. setMultiKeyMode('random');
  488. setVertexKeys([]);
  489. setVertexFileList([]);
  490. if (formApiRef.current) {
  491. formApiRef.current.setValue('vertex_files', []);
  492. }
  493. setInputs((prev) => ({ ...prev, vertex_files: [] }));
  494. }
  495. }
  496. //setAutoBan
  497. };
  498. const formatJsonField = (fieldName) => {
  499. const rawValue = (inputs?.[fieldName] ?? '').trim();
  500. if (!rawValue) return;
  501. try {
  502. const parsed = JSON.parse(rawValue);
  503. handleInputChange(fieldName, JSON.stringify(parsed, null, 2));
  504. } catch (error) {
  505. showError(`${t('JSON格式错误')}: ${error.message}`);
  506. }
  507. };
  508. const loadChannel = async () => {
  509. setLoading(true);
  510. let res = await API.get(`/api/channel/${channelId}`);
  511. if (res === undefined) {
  512. return;
  513. }
  514. const { success, message, data } = res.data;
  515. if (success) {
  516. if (data.models === '') {
  517. data.models = [];
  518. } else {
  519. data.models = data.models.split(',');
  520. }
  521. if (data.group === '') {
  522. data.groups = [];
  523. } else {
  524. data.groups = data.group.split(',');
  525. }
  526. if (data.model_mapping !== '') {
  527. data.model_mapping = JSON.stringify(
  528. JSON.parse(data.model_mapping),
  529. null,
  530. 2,
  531. );
  532. }
  533. const chInfo = data.channel_info || {};
  534. const isMulti = chInfo.is_multi_key === true;
  535. setIsMultiKeyChannel(isMulti);
  536. if (isMulti) {
  537. setBatch(true);
  538. setMultiToSingle(true);
  539. const modeVal = chInfo.multi_key_mode || 'random';
  540. setMultiKeyMode(modeVal);
  541. data.multi_key_mode = modeVal;
  542. } else {
  543. setBatch(false);
  544. setMultiToSingle(false);
  545. }
  546. // 解析渠道额外设置并合并到data中
  547. if (data.setting) {
  548. try {
  549. const parsedSettings = JSON.parse(data.setting);
  550. data.force_format = parsedSettings.force_format || false;
  551. data.thinking_to_content =
  552. parsedSettings.thinking_to_content || false;
  553. data.proxy = parsedSettings.proxy || '';
  554. data.pass_through_body_enabled =
  555. parsedSettings.pass_through_body_enabled || false;
  556. data.system_prompt = parsedSettings.system_prompt || '';
  557. data.system_prompt_override =
  558. parsedSettings.system_prompt_override || false;
  559. } catch (error) {
  560. console.error('解析渠道设置失败:', error);
  561. data.force_format = false;
  562. data.thinking_to_content = false;
  563. data.proxy = '';
  564. data.pass_through_body_enabled = false;
  565. data.system_prompt = '';
  566. data.system_prompt_override = false;
  567. }
  568. } else {
  569. data.force_format = false;
  570. data.thinking_to_content = false;
  571. data.proxy = '';
  572. data.pass_through_body_enabled = false;
  573. data.system_prompt = '';
  574. data.system_prompt_override = false;
  575. }
  576. if (data.settings) {
  577. try {
  578. const parsedSettings = JSON.parse(data.settings);
  579. data.azure_responses_version =
  580. parsedSettings.azure_responses_version || '';
  581. // 读取 Vertex 密钥格式
  582. data.vertex_key_type = parsedSettings.vertex_key_type || 'json';
  583. // 读取 AWS 密钥格式和区域
  584. data.aws_key_type = parsedSettings.aws_key_type || 'ak_sk';
  585. // 读取企业账户设置
  586. data.is_enterprise_account =
  587. parsedSettings.openrouter_enterprise === true;
  588. // 读取字段透传控制设置
  589. data.allow_service_tier = parsedSettings.allow_service_tier || false;
  590. data.disable_store = parsedSettings.disable_store || false;
  591. data.allow_safety_identifier =
  592. parsedSettings.allow_safety_identifier || false;
  593. } catch (error) {
  594. console.error('解析其他设置失败:', error);
  595. data.azure_responses_version = '';
  596. data.region = '';
  597. data.vertex_key_type = 'json';
  598. data.aws_key_type = 'ak_sk';
  599. data.is_enterprise_account = false;
  600. data.allow_service_tier = false;
  601. data.disable_store = false;
  602. data.allow_safety_identifier = false;
  603. }
  604. } else {
  605. // 兼容历史数据:老渠道没有 settings 时,默认按 json 展示
  606. data.vertex_key_type = 'json';
  607. data.aws_key_type = 'ak_sk';
  608. data.is_enterprise_account = false;
  609. data.allow_service_tier = false;
  610. data.disable_store = false;
  611. data.allow_safety_identifier = false;
  612. }
  613. if (
  614. data.type === 45 &&
  615. (!data.base_url ||
  616. (typeof data.base_url === 'string' && data.base_url.trim() === ''))
  617. ) {
  618. data.base_url = 'https://ark.cn-beijing.volces.com';
  619. }
  620. setInputs(data);
  621. if (formApiRef.current) {
  622. formApiRef.current.setValues(data);
  623. }
  624. if (data.auto_ban === 0) {
  625. setAutoBan(false);
  626. } else {
  627. setAutoBan(true);
  628. }
  629. // 同步企业账户状态
  630. setIsEnterpriseAccount(data.is_enterprise_account || false);
  631. setBasicModels(getChannelModels(data.type));
  632. // 同步更新channelSettings状态显示
  633. setChannelSettings({
  634. force_format: data.force_format,
  635. thinking_to_content: data.thinking_to_content,
  636. proxy: data.proxy,
  637. pass_through_body_enabled: data.pass_through_body_enabled,
  638. system_prompt: data.system_prompt,
  639. system_prompt_override: data.system_prompt_override || false,
  640. });
  641. initialModelsRef.current = (data.models || [])
  642. .map((model) => (model || '').trim())
  643. .filter(Boolean);
  644. initialModelMappingRef.current = data.model_mapping || '';
  645. let parsedIonet = null;
  646. if (data.other_info) {
  647. try {
  648. const maybeMeta = JSON.parse(data.other_info);
  649. if (
  650. maybeMeta &&
  651. typeof maybeMeta === 'object' &&
  652. maybeMeta.source === 'ionet'
  653. ) {
  654. parsedIonet = maybeMeta;
  655. }
  656. } catch (error) {
  657. // ignore parse error
  658. }
  659. }
  660. const managedByIonet = !!parsedIonet;
  661. setIsIonetChannel(managedByIonet);
  662. setIonetMetadata(parsedIonet);
  663. // console.log(data);
  664. } else {
  665. showError(message);
  666. }
  667. setLoading(false);
  668. };
  669. const fetchUpstreamModelList = async (name, options = {}) => {
  670. const silent = !!options.silent;
  671. // if (inputs['type'] !== 1) {
  672. // showError(t('仅支持 OpenAI 接口格式'));
  673. // return;
  674. // }
  675. setLoading(true);
  676. const models = [];
  677. let err = false;
  678. if (isEdit) {
  679. // 如果是编辑模式,使用已有的 channelId 获取模型列表
  680. const res = await API.get('/api/channel/fetch_models/' + channelId, {
  681. skipErrorHandler: true,
  682. });
  683. if (res && res.data && res.data.success) {
  684. models.push(...res.data.data);
  685. } else {
  686. err = true;
  687. }
  688. } else {
  689. // 如果是新建模式,通过后端代理获取模型列表
  690. if (!inputs?.['key']) {
  691. showError(t('请填写密钥'));
  692. err = true;
  693. } else {
  694. try {
  695. const res = await API.post(
  696. '/api/channel/fetch_models',
  697. {
  698. base_url: inputs['base_url'],
  699. type: inputs['type'],
  700. key: inputs['key'],
  701. },
  702. { skipErrorHandler: true },
  703. );
  704. if (res && res.data && res.data.success) {
  705. models.push(...res.data.data);
  706. } else {
  707. err = true;
  708. }
  709. } catch (error) {
  710. console.error('Error fetching models:', error);
  711. err = true;
  712. }
  713. }
  714. }
  715. if (!err) {
  716. const uniqueModels = Array.from(new Set(models));
  717. setFetchedModels(uniqueModels);
  718. if (!silent) {
  719. setModelModalVisible(true);
  720. }
  721. setLoading(false);
  722. return uniqueModels;
  723. } else {
  724. showError(t('获取模型列表失败'));
  725. }
  726. setLoading(false);
  727. return null;
  728. };
  729. const openModelMappingValueModal = async ({ pairKey, value }) => {
  730. const mappingKey = String(pairKey ?? '').trim();
  731. if (!mappingKey) return;
  732. if (!MODEL_FETCHABLE_TYPES.has(inputs.type)) {
  733. return;
  734. }
  735. let modelsToUse = fetchedModels;
  736. if (!Array.isArray(modelsToUse) || modelsToUse.length === 0) {
  737. const fetched = await fetchUpstreamModelList('models', { silent: true });
  738. if (Array.isArray(fetched)) {
  739. modelsToUse = fetched;
  740. }
  741. }
  742. if (!Array.isArray(modelsToUse) || modelsToUse.length === 0) {
  743. showInfo(t('暂无模型'));
  744. return;
  745. }
  746. const normalizedModelsToUse = Array.from(
  747. new Set(
  748. modelsToUse.map((model) => String(model ?? '').trim()).filter(Boolean),
  749. ),
  750. );
  751. const currentValue = String(value ?? '').trim();
  752. setModelMappingValueModalModels(normalizedModelsToUse);
  753. setModelMappingValueKey(mappingKey);
  754. setModelMappingValueSelected(
  755. normalizedModelsToUse.includes(currentValue) ? currentValue : '',
  756. );
  757. setModelMappingValueModalVisible(true);
  758. };
  759. const fetchModels = async () => {
  760. try {
  761. let res = await API.get(`/api/channel/models`);
  762. const localModelOptions = res.data.data.map((model) => {
  763. const id = (model.id || '').trim();
  764. return {
  765. key: id,
  766. label: id,
  767. value: id,
  768. };
  769. });
  770. setOriginModelOptions(localModelOptions);
  771. setFullModels(res.data.data.map((model) => model.id));
  772. setBasicModels(
  773. res.data.data
  774. .filter((model) => {
  775. return model.id.startsWith('gpt-') || model.id.startsWith('text-');
  776. })
  777. .map((model) => model.id),
  778. );
  779. } catch (error) {
  780. showError(error.message);
  781. }
  782. };
  783. const fetchGroups = async () => {
  784. try {
  785. let res = await API.get(`/api/group/`);
  786. if (res === undefined) {
  787. return;
  788. }
  789. setGroupOptions(
  790. res.data.data.map((group) => ({
  791. label: group,
  792. value: group,
  793. })),
  794. );
  795. } catch (error) {
  796. showError(error.message);
  797. }
  798. };
  799. const fetchModelGroups = async () => {
  800. try {
  801. const res = await API.get('/api/prefill_group?type=model');
  802. if (res?.data?.success) {
  803. setModelGroups(res.data.data || []);
  804. }
  805. } catch (error) {
  806. // ignore
  807. }
  808. };
  809. // 查看渠道密钥(透明验证)
  810. const handleShow2FAModal = async () => {
  811. try {
  812. // 使用 withVerification 包装,会自动处理需要验证的情况
  813. const result = await withVerification(
  814. createApiCalls.viewChannelKey(channelId),
  815. {
  816. title: t('查看渠道密钥'),
  817. description: t('为了保护账户安全,请验证您的身份。'),
  818. preferredMethod: 'passkey', // 优先使用 Passkey
  819. },
  820. );
  821. // 如果直接返回了结果(已验证),显示密钥
  822. if (result && result.success && result.data?.key) {
  823. showSuccess(t('密钥获取成功'));
  824. setKeyDisplayState({
  825. showModal: true,
  826. keyData: result.data.key,
  827. });
  828. }
  829. } catch (error) {
  830. console.error('Failed to view channel key:', error);
  831. showError(error.message || t('获取密钥失败'));
  832. }
  833. };
  834. const handleCodexOAuthGenerated = (key) => {
  835. handleInputChange('key', key);
  836. formatJsonField('key');
  837. };
  838. const handleRefreshCodexCredential = async () => {
  839. if (!isEdit) return;
  840. setCodexCredentialRefreshing(true);
  841. try {
  842. const res = await API.post(
  843. `/api/channel/${channelId}/codex/refresh`,
  844. {},
  845. { skipErrorHandler: true },
  846. );
  847. if (!res?.data?.success) {
  848. throw new Error(res?.data?.message || 'Failed to refresh credential');
  849. }
  850. showSuccess(t('凭证已刷新'));
  851. } catch (error) {
  852. showError(error.message || t('刷新失败'));
  853. } finally {
  854. setCodexCredentialRefreshing(false);
  855. }
  856. };
  857. useEffect(() => {
  858. if (inputs.type !== 45) {
  859. doubaoApiClickCountRef.current = 0;
  860. setDoubaoApiEditUnlocked(false);
  861. }
  862. }, [inputs.type]);
  863. useEffect(() => {
  864. const modelMap = new Map();
  865. originModelOptions.forEach((option) => {
  866. const v = (option.value || '').trim();
  867. if (!modelMap.has(v)) {
  868. modelMap.set(v, option);
  869. }
  870. });
  871. inputs.models.forEach((model) => {
  872. const v = (model || '').trim();
  873. if (!modelMap.has(v)) {
  874. modelMap.set(v, {
  875. key: v,
  876. label: v,
  877. value: v,
  878. });
  879. }
  880. });
  881. const categories = getModelCategories(t);
  882. const optionsWithIcon = Array.from(modelMap.values()).map((opt) => {
  883. const modelName = opt.value;
  884. let icon = null;
  885. for (const [key, category] of Object.entries(categories)) {
  886. if (key !== 'all' && category.filter({ model_name: modelName })) {
  887. icon = category.icon;
  888. break;
  889. }
  890. }
  891. return {
  892. ...opt,
  893. label: (
  894. <span className='flex items-center gap-1'>
  895. {icon}
  896. {modelName}
  897. </span>
  898. ),
  899. };
  900. });
  901. setModelOptions(optionsWithIcon);
  902. }, [originModelOptions, inputs.models, t]);
  903. useEffect(() => {
  904. fetchModels().then();
  905. fetchGroups().then();
  906. if (!isEdit) {
  907. setInputs(originInputs);
  908. if (formApiRef.current) {
  909. formApiRef.current.setValues(originInputs);
  910. }
  911. let localModels = getChannelModels(inputs.type);
  912. setBasicModels(localModels);
  913. setInputs((inputs) => ({ ...inputs, models: localModels }));
  914. }
  915. }, [props.editingChannel.id]);
  916. useEffect(() => {
  917. if (formApiRef.current) {
  918. formApiRef.current.setValues(inputs);
  919. }
  920. }, [inputs]);
  921. useEffect(() => {
  922. if (props.visible) {
  923. if (isEdit) {
  924. loadChannel();
  925. } else {
  926. formApiRef.current?.setValues(getInitValues());
  927. }
  928. fetchModelGroups();
  929. // 重置手动输入模式状态
  930. setUseManualInput(false);
  931. // 重置导航状态
  932. setCurrentSectionIndex(0);
  933. } else {
  934. // 统一的模态框关闭重置逻辑
  935. resetModalState();
  936. }
  937. }, [props.visible, channelId]);
  938. useEffect(() => {
  939. if (!isEdit) {
  940. initialModelsRef.current = [];
  941. initialModelMappingRef.current = '';
  942. }
  943. }, [isEdit, props.visible]);
  944. // 统一的模态框重置函数
  945. const resetModalState = () => {
  946. formApiRef.current?.reset();
  947. // 重置渠道设置状态
  948. setChannelSettings({
  949. force_format: false,
  950. thinking_to_content: false,
  951. proxy: '',
  952. pass_through_body_enabled: false,
  953. system_prompt: '',
  954. system_prompt_override: false,
  955. });
  956. // 重置密钥模式状态
  957. setKeyMode('append');
  958. // 重置企业账户状态
  959. setIsEnterpriseAccount(false);
  960. // 重置豆包隐藏入口状态
  961. setDoubaoApiEditUnlocked(false);
  962. doubaoApiClickCountRef.current = 0;
  963. // 清空表单中的key_mode字段
  964. if (formApiRef.current) {
  965. formApiRef.current.setValue('key_mode', undefined);
  966. }
  967. // 重置本地输入,避免下次打开残留上一次的 JSON 字段值
  968. setInputs(getInitValues());
  969. // 重置密钥显示状态
  970. resetKeyDisplayState();
  971. };
  972. const handleVertexUploadChange = ({ fileList }) => {
  973. vertexErroredNames.current.clear();
  974. (async () => {
  975. let validFiles = [];
  976. let keys = [];
  977. const errorNames = [];
  978. for (const item of fileList) {
  979. const fileObj = item.fileInstance;
  980. if (!fileObj) continue;
  981. try {
  982. const txt = await fileObj.text();
  983. keys.push(JSON.parse(txt));
  984. validFiles.push(item);
  985. } catch (err) {
  986. if (!vertexErroredNames.current.has(item.name)) {
  987. errorNames.push(item.name);
  988. vertexErroredNames.current.add(item.name);
  989. }
  990. }
  991. }
  992. // 非批量模式下只保留一个文件(最新选择的),避免重复叠加
  993. if (!batch && validFiles.length > 1) {
  994. validFiles = [validFiles[validFiles.length - 1]];
  995. keys = [keys[keys.length - 1]];
  996. }
  997. setVertexKeys(keys);
  998. setVertexFileList(validFiles);
  999. if (formApiRef.current) {
  1000. formApiRef.current.setValue('vertex_files', validFiles);
  1001. }
  1002. setInputs((prev) => ({ ...prev, vertex_files: validFiles }));
  1003. if (errorNames.length > 0) {
  1004. showError(
  1005. t('以下文件解析失败,已忽略:{{list}}', {
  1006. list: errorNames.join(', '),
  1007. }),
  1008. );
  1009. }
  1010. })();
  1011. };
  1012. const confirmMissingModelMappings = (missingModels) =>
  1013. new Promise((resolve) => {
  1014. const modal = Modal.confirm({
  1015. title: t('模型未加入列表,可能无法调用'),
  1016. content: (
  1017. <div className='text-sm leading-6'>
  1018. <div>
  1019. {t(
  1020. '模型重定向里的下列模型尚未添加到“模型”列表,调用时会因为缺少可用模型而失败:',
  1021. )}
  1022. </div>
  1023. <div className='font-mono text-xs break-all text-red-600 mt-1'>
  1024. {missingModels.join(', ')}
  1025. </div>
  1026. <div className='mt-2'>
  1027. {t(
  1028. '你可以在“自定义模型名称”处手动添加它们,然后点击填入后再提交,或者直接使用下方操作自动处理。',
  1029. )}
  1030. </div>
  1031. </div>
  1032. ),
  1033. centered: true,
  1034. footer: (
  1035. <Space align='center' className='w-full justify-end'>
  1036. <Button
  1037. type='tertiary'
  1038. onClick={() => {
  1039. modal.destroy();
  1040. resolve('cancel');
  1041. }}
  1042. >
  1043. {t('返回修改')}
  1044. </Button>
  1045. <Button
  1046. type='primary'
  1047. theme='light'
  1048. onClick={() => {
  1049. modal.destroy();
  1050. resolve('submit');
  1051. }}
  1052. >
  1053. {t('直接提交')}
  1054. </Button>
  1055. <Button
  1056. type='primary'
  1057. theme='solid'
  1058. onClick={() => {
  1059. modal.destroy();
  1060. resolve('add');
  1061. }}
  1062. >
  1063. {t('添加后提交')}
  1064. </Button>
  1065. </Space>
  1066. ),
  1067. });
  1068. });
  1069. const hasModelConfigChanged = (normalizedModels, modelMappingStr) => {
  1070. if (!isEdit) return true;
  1071. const initialModels = initialModelsRef.current;
  1072. if (normalizedModels.length !== initialModels.length) {
  1073. return true;
  1074. }
  1075. for (let i = 0; i < normalizedModels.length; i++) {
  1076. if (normalizedModels[i] !== initialModels[i]) {
  1077. return true;
  1078. }
  1079. }
  1080. const normalizedMapping = (modelMappingStr || '').trim();
  1081. const initialMapping = (initialModelMappingRef.current || '').trim();
  1082. return normalizedMapping !== initialMapping;
  1083. };
  1084. const submit = async () => {
  1085. const formValues = formApiRef.current ? formApiRef.current.getValues() : {};
  1086. let localInputs = { ...formValues };
  1087. if (localInputs.type === 57) {
  1088. if (batch) {
  1089. showInfo(t('Codex 渠道不支持批量创建'));
  1090. return;
  1091. }
  1092. const rawKey = (localInputs.key || '').trim();
  1093. if (!isEdit && rawKey === '') {
  1094. showInfo(t('请输入密钥!'));
  1095. return;
  1096. }
  1097. if (rawKey !== '') {
  1098. if (!verifyJSON(rawKey)) {
  1099. showInfo(t('密钥必须是合法的 JSON 格式!'));
  1100. return;
  1101. }
  1102. try {
  1103. const parsed = JSON.parse(rawKey);
  1104. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
  1105. showInfo(t('密钥必须是 JSON 对象'));
  1106. return;
  1107. }
  1108. const accessToken = String(parsed.access_token || '').trim();
  1109. const accountId = String(parsed.account_id || '').trim();
  1110. if (!accessToken) {
  1111. showInfo(t('密钥 JSON 必须包含 access_token'));
  1112. return;
  1113. }
  1114. if (!accountId) {
  1115. showInfo(t('密钥 JSON 必须包含 account_id'));
  1116. return;
  1117. }
  1118. localInputs.key = JSON.stringify(parsed);
  1119. } catch (error) {
  1120. showInfo(t('密钥必须是合法的 JSON 格式!'));
  1121. return;
  1122. }
  1123. }
  1124. }
  1125. if (localInputs.type === 41) {
  1126. const keyType = localInputs.vertex_key_type || 'json';
  1127. if (keyType === 'api_key') {
  1128. // 直接作为普通字符串密钥处理
  1129. if (!isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
  1130. showInfo(t('请输入密钥!'));
  1131. return;
  1132. }
  1133. } else {
  1134. // JSON 服务账号密钥
  1135. if (useManualInput) {
  1136. if (localInputs.key && localInputs.key.trim() !== '') {
  1137. try {
  1138. const parsedKey = JSON.parse(localInputs.key);
  1139. localInputs.key = JSON.stringify(parsedKey);
  1140. } catch (err) {
  1141. showError(t('密钥格式无效,请输入有效的 JSON 格式密钥'));
  1142. return;
  1143. }
  1144. } else if (!isEdit) {
  1145. showInfo(t('请输入密钥!'));
  1146. return;
  1147. }
  1148. } else {
  1149. // 文件上传模式
  1150. let keys = vertexKeys;
  1151. if (keys.length === 0 && vertexFileList.length > 0) {
  1152. try {
  1153. const parsed = await Promise.all(
  1154. vertexFileList.map(async (item) => {
  1155. const fileObj = item.fileInstance;
  1156. if (!fileObj) return null;
  1157. const txt = await fileObj.text();
  1158. return JSON.parse(txt);
  1159. }),
  1160. );
  1161. keys = parsed.filter(Boolean);
  1162. } catch (err) {
  1163. showError(t('解析密钥文件失败: {{msg}}', { msg: err.message }));
  1164. return;
  1165. }
  1166. }
  1167. if (keys.length === 0) {
  1168. if (!isEdit) {
  1169. showInfo(t('请上传密钥文件!'));
  1170. return;
  1171. } else {
  1172. delete localInputs.key;
  1173. }
  1174. } else {
  1175. localInputs.key = batch
  1176. ? JSON.stringify(keys)
  1177. : JSON.stringify(keys[0]);
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // 如果是编辑模式且 key 为空字符串,避免提交空值覆盖旧密钥
  1183. if (isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
  1184. delete localInputs.key;
  1185. }
  1186. delete localInputs.vertex_files;
  1187. if (!isEdit && (!localInputs.name || !localInputs.key)) {
  1188. showInfo(t('请填写渠道名称和渠道密钥!'));
  1189. return;
  1190. }
  1191. if (!Array.isArray(localInputs.models) || localInputs.models.length === 0) {
  1192. showInfo(t('请至少选择一个模型!'));
  1193. return;
  1194. }
  1195. if (
  1196. localInputs.type === 45 &&
  1197. (!localInputs.base_url || localInputs.base_url.trim() === '')
  1198. ) {
  1199. showInfo(t('请输入API地址!'));
  1200. return;
  1201. }
  1202. const hasModelMapping =
  1203. typeof localInputs.model_mapping === 'string' &&
  1204. localInputs.model_mapping.trim() !== '';
  1205. let parsedModelMapping = null;
  1206. if (hasModelMapping) {
  1207. if (!verifyJSON(localInputs.model_mapping)) {
  1208. showInfo(t('模型映射必须是合法的 JSON 格式!'));
  1209. return;
  1210. }
  1211. try {
  1212. parsedModelMapping = JSON.parse(localInputs.model_mapping);
  1213. } catch (error) {
  1214. showInfo(t('模型映射必须是合法的 JSON 格式!'));
  1215. return;
  1216. }
  1217. }
  1218. const normalizedModels = (localInputs.models || [])
  1219. .map((model) => (model || '').trim())
  1220. .filter(Boolean);
  1221. localInputs.models = normalizedModels;
  1222. if (
  1223. parsedModelMapping &&
  1224. typeof parsedModelMapping === 'object' &&
  1225. !Array.isArray(parsedModelMapping)
  1226. ) {
  1227. const modelSet = new Set(normalizedModels);
  1228. const missingModels = Object.keys(parsedModelMapping)
  1229. .map((key) => (key || '').trim())
  1230. .filter((key) => key && !modelSet.has(key));
  1231. const shouldPromptMissing =
  1232. missingModels.length > 0 &&
  1233. hasModelConfigChanged(normalizedModels, localInputs.model_mapping);
  1234. if (shouldPromptMissing) {
  1235. const confirmAction = await confirmMissingModelMappings(missingModels);
  1236. if (confirmAction === 'cancel') {
  1237. return;
  1238. }
  1239. if (confirmAction === 'add') {
  1240. const updatedModels = Array.from(
  1241. new Set([...normalizedModels, ...missingModels]),
  1242. );
  1243. localInputs.models = updatedModels;
  1244. handleInputChange('models', updatedModels);
  1245. }
  1246. }
  1247. }
  1248. if (localInputs.base_url && localInputs.base_url.endsWith('/')) {
  1249. localInputs.base_url = localInputs.base_url.slice(
  1250. 0,
  1251. localInputs.base_url.length - 1,
  1252. );
  1253. }
  1254. if (localInputs.type === 18 && localInputs.other === '') {
  1255. localInputs.other = 'v2.1';
  1256. }
  1257. // 生成渠道额外设置JSON
  1258. const channelExtraSettings = {
  1259. force_format: localInputs.force_format || false,
  1260. thinking_to_content: localInputs.thinking_to_content || false,
  1261. proxy: localInputs.proxy || '',
  1262. pass_through_body_enabled: localInputs.pass_through_body_enabled || false,
  1263. system_prompt: localInputs.system_prompt || '',
  1264. system_prompt_override: localInputs.system_prompt_override || false,
  1265. };
  1266. localInputs.setting = JSON.stringify(channelExtraSettings);
  1267. // 处理 settings 字段(包括企业账户设置和字段透传控制)
  1268. let settings = {};
  1269. if (localInputs.settings) {
  1270. try {
  1271. settings = JSON.parse(localInputs.settings);
  1272. } catch (error) {
  1273. console.error('解析settings失败:', error);
  1274. }
  1275. }
  1276. // type === 20: 设置企业账户标识,无论是true还是false都要传到后端
  1277. if (localInputs.type === 20) {
  1278. settings.openrouter_enterprise =
  1279. localInputs.is_enterprise_account === true;
  1280. }
  1281. // type === 33 (AWS): 保存 aws_key_type 到 settings
  1282. if (localInputs.type === 33) {
  1283. settings.aws_key_type = localInputs.aws_key_type || 'ak_sk';
  1284. }
  1285. // type === 41 (Vertex): 始终保存 vertex_key_type 到 settings,避免编辑时被重置
  1286. if (localInputs.type === 41) {
  1287. settings.vertex_key_type = localInputs.vertex_key_type || 'json';
  1288. } else if ('vertex_key_type' in settings) {
  1289. delete settings.vertex_key_type;
  1290. }
  1291. // type === 1 (OpenAI) 或 type === 14 (Claude): 设置字段透传控制(显式保存布尔值)
  1292. if (localInputs.type === 1 || localInputs.type === 14) {
  1293. settings.allow_service_tier = localInputs.allow_service_tier === true;
  1294. // 仅 OpenAI 渠道需要 store 和 safety_identifier
  1295. if (localInputs.type === 1) {
  1296. settings.disable_store = localInputs.disable_store === true;
  1297. settings.allow_safety_identifier =
  1298. localInputs.allow_safety_identifier === true;
  1299. }
  1300. }
  1301. localInputs.settings = JSON.stringify(settings);
  1302. // 清理不需要发送到后端的字段
  1303. delete localInputs.force_format;
  1304. delete localInputs.thinking_to_content;
  1305. delete localInputs.proxy;
  1306. delete localInputs.pass_through_body_enabled;
  1307. delete localInputs.system_prompt;
  1308. delete localInputs.system_prompt_override;
  1309. delete localInputs.is_enterprise_account;
  1310. // 顶层的 vertex_key_type 不应发送给后端
  1311. delete localInputs.vertex_key_type;
  1312. // 顶层的 aws_key_type 不应发送给后端
  1313. delete localInputs.aws_key_type;
  1314. // 清理字段透传控制的临时字段
  1315. delete localInputs.allow_service_tier;
  1316. delete localInputs.disable_store;
  1317. delete localInputs.allow_safety_identifier;
  1318. let res;
  1319. localInputs.auto_ban = localInputs.auto_ban ? 1 : 0;
  1320. localInputs.models = localInputs.models.join(',');
  1321. localInputs.group = (localInputs.groups || []).join(',');
  1322. let mode = 'single';
  1323. if (batch) {
  1324. mode = multiToSingle ? 'multi_to_single' : 'batch';
  1325. }
  1326. if (isEdit) {
  1327. res = await API.put(`/api/channel/`, {
  1328. ...localInputs,
  1329. id: parseInt(channelId),
  1330. key_mode: isMultiKeyChannel ? keyMode : undefined, // 只在多key模式下传递
  1331. });
  1332. } else {
  1333. res = await API.post(`/api/channel/`, {
  1334. mode: mode,
  1335. multi_key_mode: mode === 'multi_to_single' ? multiKeyMode : undefined,
  1336. channel: localInputs,
  1337. });
  1338. }
  1339. const { success, message } = res.data;
  1340. if (success) {
  1341. if (isEdit) {
  1342. showSuccess(t('渠道更新成功!'));
  1343. } else {
  1344. showSuccess(t('渠道创建成功!'));
  1345. setInputs(originInputs);
  1346. }
  1347. props.refresh();
  1348. props.handleClose();
  1349. } else {
  1350. showError(message);
  1351. }
  1352. };
  1353. // 密钥去重函数
  1354. const deduplicateKeys = () => {
  1355. const currentKey = formApiRef.current?.getValue('key') || inputs.key || '';
  1356. if (!currentKey.trim()) {
  1357. showInfo(t('请先输入密钥'));
  1358. return;
  1359. }
  1360. // 按行分割密钥
  1361. const keyLines = currentKey.split('\n');
  1362. const beforeCount = keyLines.length;
  1363. // 使用哈希表去重,保持原有顺序
  1364. const keySet = new Set();
  1365. const deduplicatedKeys = [];
  1366. keyLines.forEach((line) => {
  1367. const trimmedLine = line.trim();
  1368. if (trimmedLine && !keySet.has(trimmedLine)) {
  1369. keySet.add(trimmedLine);
  1370. deduplicatedKeys.push(trimmedLine);
  1371. }
  1372. });
  1373. const afterCount = deduplicatedKeys.length;
  1374. const deduplicatedKeyText = deduplicatedKeys.join('\n');
  1375. // 更新表单和状态
  1376. if (formApiRef.current) {
  1377. formApiRef.current.setValue('key', deduplicatedKeyText);
  1378. }
  1379. handleInputChange('key', deduplicatedKeyText);
  1380. // 显示去重结果
  1381. const message = t(
  1382. '去重完成:去重前 {{before}} 个密钥,去重后 {{after}} 个密钥',
  1383. {
  1384. before: beforeCount,
  1385. after: afterCount,
  1386. },
  1387. );
  1388. if (beforeCount === afterCount) {
  1389. showInfo(t('未发现重复密钥'));
  1390. } else {
  1391. showSuccess(message);
  1392. }
  1393. };
  1394. const addCustomModels = () => {
  1395. if (customModel.trim() === '') return;
  1396. const modelArray = customModel.split(',').map((model) => model.trim());
  1397. let localModels = [...inputs.models];
  1398. let localModelOptions = [...modelOptions];
  1399. const addedModels = [];
  1400. modelArray.forEach((model) => {
  1401. if (model && !localModels.includes(model)) {
  1402. localModels.push(model);
  1403. localModelOptions.push({
  1404. key: model,
  1405. label: model,
  1406. value: model,
  1407. });
  1408. addedModels.push(model);
  1409. }
  1410. });
  1411. setModelOptions(localModelOptions);
  1412. setCustomModel('');
  1413. handleInputChange('models', localModels);
  1414. if (addedModels.length > 0) {
  1415. showSuccess(
  1416. t('已新增 {{count}} 个模型:{{list}}', {
  1417. count: addedModels.length,
  1418. list: addedModels.join(', '),
  1419. }),
  1420. );
  1421. } else {
  1422. showInfo(t('未发现新增模型'));
  1423. }
  1424. };
  1425. const batchAllowed = (!isEdit || isMultiKeyChannel) && inputs.type !== 57;
  1426. const batchExtra = batchAllowed ? (
  1427. <Space>
  1428. {!isEdit && (
  1429. <Checkbox
  1430. disabled={isEdit}
  1431. checked={batch}
  1432. onChange={(e) => {
  1433. const checked = e.target.checked;
  1434. if (!checked && vertexFileList.length > 1) {
  1435. Modal.confirm({
  1436. title: t('切换为单密钥模式'),
  1437. content: t(
  1438. '将仅保留第一个密钥文件,其余文件将被移除,是否继续?',
  1439. ),
  1440. onOk: () => {
  1441. const firstFile = vertexFileList[0];
  1442. const firstKey = vertexKeys[0] ? [vertexKeys[0]] : [];
  1443. setVertexFileList([firstFile]);
  1444. setVertexKeys(firstKey);
  1445. formApiRef.current?.setValue('vertex_files', [firstFile]);
  1446. setInputs((prev) => ({ ...prev, vertex_files: [firstFile] }));
  1447. setBatch(false);
  1448. setMultiToSingle(false);
  1449. setMultiKeyMode('random');
  1450. },
  1451. onCancel: () => {
  1452. setBatch(true);
  1453. },
  1454. centered: true,
  1455. });
  1456. return;
  1457. }
  1458. setBatch(checked);
  1459. if (!checked) {
  1460. setMultiToSingle(false);
  1461. setMultiKeyMode('random');
  1462. } else {
  1463. // 批量模式下禁用手动输入,并清空手动输入的内容
  1464. setUseManualInput(false);
  1465. if (inputs.type === 41) {
  1466. // 清空手动输入的密钥内容
  1467. if (formApiRef.current) {
  1468. formApiRef.current.setValue('key', '');
  1469. }
  1470. handleInputChange('key', '');
  1471. }
  1472. }
  1473. }}
  1474. >
  1475. {t('批量创建')}
  1476. </Checkbox>
  1477. )}
  1478. {batch && (
  1479. <>
  1480. <Checkbox
  1481. disabled={isEdit}
  1482. checked={multiToSingle}
  1483. onChange={() => {
  1484. setMultiToSingle((prev) => {
  1485. const nextValue = !prev;
  1486. setInputs((prevInputs) => {
  1487. const newInputs = { ...prevInputs };
  1488. if (nextValue) {
  1489. newInputs.multi_key_mode = multiKeyMode;
  1490. } else {
  1491. delete newInputs.multi_key_mode;
  1492. }
  1493. return newInputs;
  1494. });
  1495. return nextValue;
  1496. });
  1497. }}
  1498. >
  1499. {t('密钥聚合模式')}
  1500. </Checkbox>
  1501. {inputs.type !== 41 && (
  1502. <Button
  1503. size='small'
  1504. type='tertiary'
  1505. theme='outline'
  1506. onClick={deduplicateKeys}
  1507. style={{ textDecoration: 'underline' }}
  1508. >
  1509. {t('密钥去重')}
  1510. </Button>
  1511. )}
  1512. </>
  1513. )}
  1514. </Space>
  1515. ) : null;
  1516. const channelOptionList = useMemo(
  1517. () =>
  1518. CHANNEL_OPTIONS.map((opt) => ({
  1519. ...opt,
  1520. // 保持 label 为纯文本以支持搜索
  1521. label: opt.label,
  1522. })),
  1523. [],
  1524. );
  1525. const renderChannelOption = (renderProps) => {
  1526. const {
  1527. disabled,
  1528. selected,
  1529. label,
  1530. value,
  1531. focused,
  1532. className,
  1533. style,
  1534. onMouseEnter,
  1535. onClick,
  1536. ...rest
  1537. } = renderProps;
  1538. const searchWords = channelSearchValue ? [channelSearchValue] : [];
  1539. // 构建样式类名
  1540. const optionClassName = [
  1541. 'flex items-center gap-3 px-3 py-2 transition-all duration-200 rounded-lg mx-2 my-1',
  1542. focused && 'bg-blue-50 shadow-sm',
  1543. selected &&
  1544. 'bg-blue-100 text-blue-700 shadow-lg ring-2 ring-blue-200 ring-opacity-50',
  1545. disabled && 'opacity-50 cursor-not-allowed',
  1546. !disabled && 'hover:bg-gray-50 hover:shadow-md cursor-pointer',
  1547. className,
  1548. ]
  1549. .filter(Boolean)
  1550. .join(' ');
  1551. return (
  1552. <div
  1553. style={style}
  1554. className={optionClassName}
  1555. onClick={() => !disabled && onClick()}
  1556. onMouseEnter={(e) => onMouseEnter()}
  1557. >
  1558. <div className='flex items-center gap-3 w-full'>
  1559. <div className='flex-shrink-0 w-5 h-5 flex items-center justify-center'>
  1560. {getChannelIcon(value)}
  1561. </div>
  1562. <div className='flex-1 min-w-0'>
  1563. <Highlight
  1564. sourceString={label}
  1565. searchWords={searchWords}
  1566. className='text-sm font-medium truncate'
  1567. />
  1568. </div>
  1569. {selected && (
  1570. <div className='flex-shrink-0 text-blue-600'>
  1571. <svg
  1572. width='16'
  1573. height='16'
  1574. viewBox='0 0 16 16'
  1575. fill='currentColor'
  1576. >
  1577. <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' />
  1578. </svg>
  1579. </div>
  1580. )}
  1581. </div>
  1582. </div>
  1583. );
  1584. };
  1585. return (
  1586. <>
  1587. <SideSheet
  1588. placement={isEdit ? 'right' : 'left'}
  1589. title={
  1590. <Space>
  1591. <Tag color='blue' shape='circle'>
  1592. {isEdit ? t('编辑') : t('新建')}
  1593. </Tag>
  1594. <Title heading={4} className='m-0'>
  1595. {isEdit ? t('更新渠道信息') : t('创建新的渠道')}
  1596. </Title>
  1597. </Space>
  1598. }
  1599. bodyStyle={{ padding: '0' }}
  1600. visible={props.visible}
  1601. width={isMobile ? '100%' : 600}
  1602. footer={
  1603. <div className='flex justify-between items-center bg-white'>
  1604. <div className='flex gap-2'>
  1605. <Button
  1606. size='small'
  1607. type='tertiary'
  1608. icon={<IconChevronUp />}
  1609. onClick={() => navigateToSection('up')}
  1610. style={{
  1611. borderRadius: '50%',
  1612. width: '32px',
  1613. height: '32px',
  1614. padding: 0,
  1615. display: 'flex',
  1616. alignItems: 'center',
  1617. justifyContent: 'center',
  1618. }}
  1619. title={t('上一个表单块')}
  1620. />
  1621. <Button
  1622. size='small'
  1623. type='tertiary'
  1624. icon={<IconChevronDown />}
  1625. onClick={() => navigateToSection('down')}
  1626. style={{
  1627. borderRadius: '50%',
  1628. width: '32px',
  1629. height: '32px',
  1630. padding: 0,
  1631. display: 'flex',
  1632. alignItems: 'center',
  1633. justifyContent: 'center',
  1634. }}
  1635. title={t('下一个表单块')}
  1636. />
  1637. </div>
  1638. <Space>
  1639. <Button
  1640. theme='solid'
  1641. onClick={() => formApiRef.current?.submitForm()}
  1642. icon={<IconSave />}
  1643. >
  1644. {t('提交')}
  1645. </Button>
  1646. <Button
  1647. theme='light'
  1648. type='primary'
  1649. onClick={handleCancel}
  1650. icon={<IconClose />}
  1651. >
  1652. {t('取消')}
  1653. </Button>
  1654. </Space>
  1655. </div>
  1656. }
  1657. closeIcon={null}
  1658. onCancel={() => handleCancel()}
  1659. >
  1660. <Form
  1661. key={isEdit ? 'edit' : 'new'}
  1662. initValues={originInputs}
  1663. getFormApi={(api) => (formApiRef.current = api)}
  1664. onSubmit={submit}
  1665. >
  1666. {() => (
  1667. <Spin spinning={loading}>
  1668. <div className='p-2 space-y-3' ref={formContainerRef}>
  1669. <div ref={(el) => (formSectionRefs.current.basicInfo = el)}>
  1670. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  1671. {/* Header: Basic Info */}
  1672. <div className='flex items-center mb-2'>
  1673. <Avatar
  1674. size='small'
  1675. color='blue'
  1676. className='mr-2 shadow-md'
  1677. >
  1678. <IconServer size={16} />
  1679. </Avatar>
  1680. <div>
  1681. <Text className='text-lg font-medium'>
  1682. {t('基本信息')}
  1683. </Text>
  1684. <div className='text-xs text-gray-600'>
  1685. {t('渠道的基本配置信息')}
  1686. </div>
  1687. </div>
  1688. </div>
  1689. {isIonetChannel && (
  1690. <Banner
  1691. type='info'
  1692. closeIcon={null}
  1693. className='mb-4 rounded-xl'
  1694. description={t(
  1695. '此渠道由 IO.NET 自动同步,类型、密钥和 API 地址已锁定。',
  1696. )}
  1697. >
  1698. <Space>
  1699. {ionetMetadata?.deployment_id && (
  1700. <Button
  1701. size='small'
  1702. theme='light'
  1703. type='primary'
  1704. icon={<IconGlobe />}
  1705. onClick={handleOpenIonetDeployment}
  1706. >
  1707. {t('查看关联部署')}
  1708. </Button>
  1709. )}
  1710. </Space>
  1711. </Banner>
  1712. )}
  1713. <Form.Select
  1714. field='type'
  1715. label={t('类型')}
  1716. placeholder={t('请选择渠道类型')}
  1717. rules={[{ required: true, message: t('请选择渠道类型') }]}
  1718. optionList={channelOptionList}
  1719. style={{ width: '100%' }}
  1720. filter={selectFilter}
  1721. autoClearSearchValue={false}
  1722. searchPosition='dropdown'
  1723. onSearch={(value) => setChannelSearchValue(value)}
  1724. renderOptionItem={renderChannelOption}
  1725. onChange={(value) => handleInputChange('type', value)}
  1726. disabled={isIonetLocked}
  1727. />
  1728. {inputs.type === 20 && (
  1729. <Form.Switch
  1730. field='is_enterprise_account'
  1731. label={t('是否为企业账户')}
  1732. checkedText={t('是')}
  1733. uncheckedText={t('否')}
  1734. onChange={(value) => {
  1735. setIsEnterpriseAccount(value);
  1736. handleInputChange('is_enterprise_account', value);
  1737. }}
  1738. extraText={t(
  1739. '企业账户为特殊返回格式,需要特殊处理,如果非企业账户,请勿勾选',
  1740. )}
  1741. initValue={inputs.is_enterprise_account}
  1742. />
  1743. )}
  1744. <Form.Input
  1745. field='name'
  1746. label={t('名称')}
  1747. placeholder={t('请为渠道命名')}
  1748. rules={[{ required: true, message: t('请为渠道命名') }]}
  1749. showClear
  1750. onChange={(value) => handleInputChange('name', value)}
  1751. autoComplete='new-password'
  1752. />
  1753. {inputs.type === 33 && (
  1754. <>
  1755. <Form.Select
  1756. field='aws_key_type'
  1757. label={t('密钥格式')}
  1758. placeholder={t('请选择密钥格式')}
  1759. optionList={[
  1760. {
  1761. label: 'AccessKey / SecretAccessKey',
  1762. value: 'ak_sk',
  1763. },
  1764. { label: 'API Key', value: 'api_key' },
  1765. ]}
  1766. style={{ width: '100%' }}
  1767. value={inputs.aws_key_type || 'ak_sk'}
  1768. onChange={(value) => {
  1769. handleChannelOtherSettingsChange(
  1770. 'aws_key_type',
  1771. value,
  1772. );
  1773. }}
  1774. extraText={t(
  1775. 'AK/SK 模式:使用 AccessKey 和 SecretAccessKey;API Key 模式:使用 API Key',
  1776. )}
  1777. />
  1778. </>
  1779. )}
  1780. {inputs.type === 41 && (
  1781. <Form.Select
  1782. field='vertex_key_type'
  1783. label={t('密钥格式')}
  1784. placeholder={t('请选择密钥格式')}
  1785. optionList={[
  1786. { label: 'JSON', value: 'json' },
  1787. { label: 'API Key', value: 'api_key' },
  1788. ]}
  1789. style={{ width: '100%' }}
  1790. value={inputs.vertex_key_type || 'json'}
  1791. onChange={(value) => {
  1792. // 更新设置中的 vertex_key_type
  1793. handleChannelOtherSettingsChange(
  1794. 'vertex_key_type',
  1795. value,
  1796. );
  1797. // 切换为 api_key 时,关闭批量与手动/文件切换,并清理已选文件
  1798. if (value === 'api_key') {
  1799. setBatch(false);
  1800. setUseManualInput(false);
  1801. setVertexKeys([]);
  1802. setVertexFileList([]);
  1803. if (formApiRef.current) {
  1804. formApiRef.current.setValue('vertex_files', []);
  1805. }
  1806. }
  1807. }}
  1808. extraText={
  1809. inputs.vertex_key_type === 'api_key'
  1810. ? t('API Key 模式下不支持批量创建')
  1811. : t('JSON 模式支持手动输入或上传服务账号 JSON')
  1812. }
  1813. />
  1814. )}
  1815. {batch ? (
  1816. inputs.type === 41 &&
  1817. (inputs.vertex_key_type || 'json') === 'json' ? (
  1818. <Form.Upload
  1819. field='vertex_files'
  1820. label={t('密钥文件 (.json)')}
  1821. accept='.json'
  1822. multiple
  1823. draggable
  1824. dragIcon={<IconBolt />}
  1825. dragMainText={t('点击上传文件或拖拽文件到这里')}
  1826. dragSubText={t('仅支持 JSON 文件,支持多文件')}
  1827. style={{ marginTop: 10 }}
  1828. uploadTrigger='custom'
  1829. beforeUpload={() => false}
  1830. onChange={handleVertexUploadChange}
  1831. fileList={vertexFileList}
  1832. rules={
  1833. isEdit
  1834. ? []
  1835. : [
  1836. {
  1837. required: true,
  1838. message: t('请上传密钥文件'),
  1839. },
  1840. ]
  1841. }
  1842. extraText={batchExtra}
  1843. />
  1844. ) : (
  1845. <Form.TextArea
  1846. field='key'
  1847. label={t('密钥')}
  1848. placeholder={
  1849. inputs.type === 33
  1850. ? inputs.aws_key_type === 'api_key'
  1851. ? t(
  1852. '请输入 API Key,一行一个,格式:APIKey|Region',
  1853. )
  1854. : t(
  1855. '请输入密钥,一行一个,格式:AccessKey|SecretAccessKey|Region',
  1856. )
  1857. : t('请输入密钥,一行一个')
  1858. }
  1859. rules={
  1860. isEdit
  1861. ? []
  1862. : [{ required: true, message: t('请输入密钥') }]
  1863. }
  1864. autosize
  1865. autoComplete='new-password'
  1866. onChange={(value) => handleInputChange('key', value)}
  1867. disabled={isIonetLocked}
  1868. extraText={
  1869. <div className='flex items-center gap-2 flex-wrap'>
  1870. {isEdit &&
  1871. isMultiKeyChannel &&
  1872. keyMode === 'append' && (
  1873. <Text type='warning' size='small'>
  1874. {t(
  1875. '追加模式:新密钥将添加到现有密钥列表的末尾',
  1876. )}
  1877. </Text>
  1878. )}
  1879. {isEdit && (
  1880. <Button
  1881. size='small'
  1882. type='primary'
  1883. theme='outline'
  1884. onClick={handleShow2FAModal}
  1885. >
  1886. {t('查看密钥')}
  1887. </Button>
  1888. )}
  1889. {batchExtra}
  1890. </div>
  1891. }
  1892. showClear
  1893. />
  1894. )
  1895. ) : (
  1896. <>
  1897. {inputs.type === 57 ? (
  1898. <>
  1899. <Form.TextArea
  1900. field='key'
  1901. label={
  1902. isEdit
  1903. ? t('密钥(编辑模式下,保存的密钥不会显示)')
  1904. : t('密钥')
  1905. }
  1906. placeholder={t(
  1907. '请输入 JSON 格式的 OAuth 凭据,例如:\n{\n "access_token": "...",\n "account_id": "..." \n}',
  1908. )}
  1909. rules={
  1910. isEdit
  1911. ? []
  1912. : [
  1913. {
  1914. required: true,
  1915. message: t('请输入密钥'),
  1916. },
  1917. ]
  1918. }
  1919. autoComplete='new-password'
  1920. onChange={(value) =>
  1921. handleInputChange('key', value)
  1922. }
  1923. disabled={isIonetLocked}
  1924. extraText={
  1925. <div className='flex flex-col gap-2'>
  1926. <Text type='tertiary' size='small'>
  1927. {t(
  1928. '仅支持 JSON 对象,必须包含 access_token 与 account_id',
  1929. )}
  1930. </Text>
  1931. <Space wrap spacing='tight'>
  1932. <Button
  1933. size='small'
  1934. type='primary'
  1935. theme='outline'
  1936. onClick={() =>
  1937. setCodexOAuthModalVisible(true)
  1938. }
  1939. disabled={isIonetLocked}
  1940. >
  1941. {t('Codex 授权')}
  1942. </Button>
  1943. {isEdit && (
  1944. <Button
  1945. size='small'
  1946. type='primary'
  1947. theme='outline'
  1948. onClick={handleRefreshCodexCredential}
  1949. loading={codexCredentialRefreshing}
  1950. disabled={isIonetLocked}
  1951. >
  1952. {t('刷新凭证')}
  1953. </Button>
  1954. )}
  1955. <Button
  1956. size='small'
  1957. type='primary'
  1958. theme='outline'
  1959. onClick={() => formatJsonField('key')}
  1960. disabled={isIonetLocked}
  1961. >
  1962. {t('格式化')}
  1963. </Button>
  1964. {isEdit && (
  1965. <Button
  1966. size='small'
  1967. type='primary'
  1968. theme='outline'
  1969. onClick={handleShow2FAModal}
  1970. disabled={isIonetLocked}
  1971. >
  1972. {t('查看密钥')}
  1973. </Button>
  1974. )}
  1975. {batchExtra}
  1976. </Space>
  1977. </div>
  1978. }
  1979. autosize
  1980. showClear
  1981. />
  1982. <CodexOAuthModal
  1983. visible={codexOAuthModalVisible}
  1984. onCancel={() => setCodexOAuthModalVisible(false)}
  1985. onSuccess={handleCodexOAuthGenerated}
  1986. />
  1987. </>
  1988. ) : inputs.type === 41 &&
  1989. (inputs.vertex_key_type || 'json') === 'json' ? (
  1990. <>
  1991. {!batch && (
  1992. <div className='flex items-center justify-between mb-3'>
  1993. <Text className='text-sm font-medium'>
  1994. {t('密钥输入方式')}
  1995. </Text>
  1996. <Space>
  1997. <Button
  1998. size='small'
  1999. type={
  2000. !useManualInput ? 'primary' : 'tertiary'
  2001. }
  2002. onClick={() => {
  2003. setUseManualInput(false);
  2004. // 切换到文件上传模式时清空手动输入的密钥
  2005. if (formApiRef.current) {
  2006. formApiRef.current.setValue('key', '');
  2007. }
  2008. handleInputChange('key', '');
  2009. }}
  2010. >
  2011. {t('文件上传')}
  2012. </Button>
  2013. <Button
  2014. size='small'
  2015. type={
  2016. useManualInput ? 'primary' : 'tertiary'
  2017. }
  2018. onClick={() => {
  2019. setUseManualInput(true);
  2020. // 切换到手动输入模式时清空文件上传相关状态
  2021. setVertexKeys([]);
  2022. setVertexFileList([]);
  2023. if (formApiRef.current) {
  2024. formApiRef.current.setValue(
  2025. 'vertex_files',
  2026. [],
  2027. );
  2028. }
  2029. setInputs((prev) => ({
  2030. ...prev,
  2031. vertex_files: [],
  2032. }));
  2033. }}
  2034. >
  2035. {t('手动输入')}
  2036. </Button>
  2037. </Space>
  2038. </div>
  2039. )}
  2040. {batch && (
  2041. <Banner
  2042. type='info'
  2043. description={t(
  2044. '批量创建模式下仅支持文件上传,不支持手动输入',
  2045. )}
  2046. className='!rounded-lg mb-3'
  2047. />
  2048. )}
  2049. {useManualInput && !batch ? (
  2050. <Form.TextArea
  2051. field='key'
  2052. label={
  2053. isEdit
  2054. ? t(
  2055. '密钥(编辑模式下,保存的密钥不会显示)',
  2056. )
  2057. : t('密钥')
  2058. }
  2059. placeholder={t(
  2060. '请输入 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}',
  2061. )}
  2062. rules={
  2063. isEdit
  2064. ? []
  2065. : [
  2066. {
  2067. required: true,
  2068. message: t('请输入密钥'),
  2069. },
  2070. ]
  2071. }
  2072. autoComplete='new-password'
  2073. onChange={(value) =>
  2074. handleInputChange('key', value)
  2075. }
  2076. extraText={
  2077. <div className='flex items-center gap-2'>
  2078. <Text type='tertiary' size='small'>
  2079. {t('请输入完整的 JSON 格式密钥内容')}
  2080. </Text>
  2081. {isEdit &&
  2082. isMultiKeyChannel &&
  2083. keyMode === 'append' && (
  2084. <Text type='warning' size='small'>
  2085. {t(
  2086. '追加模式:新密钥将添加到现有密钥列表的末尾',
  2087. )}
  2088. </Text>
  2089. )}
  2090. {isEdit && (
  2091. <Button
  2092. size='small'
  2093. type='primary'
  2094. theme='outline'
  2095. onClick={handleShow2FAModal}
  2096. >
  2097. {t('查看密钥')}
  2098. </Button>
  2099. )}
  2100. {batchExtra}
  2101. </div>
  2102. }
  2103. autosize
  2104. showClear
  2105. />
  2106. ) : (
  2107. <Form.Upload
  2108. field='vertex_files'
  2109. label={t('密钥文件 (.json)')}
  2110. accept='.json'
  2111. draggable
  2112. dragIcon={<IconBolt />}
  2113. dragMainText={t('点击上传文件或拖拽文件到这里')}
  2114. dragSubText={t('仅支持 JSON 文件')}
  2115. style={{ marginTop: 10 }}
  2116. uploadTrigger='custom'
  2117. beforeUpload={() => false}
  2118. onChange={handleVertexUploadChange}
  2119. fileList={vertexFileList}
  2120. rules={
  2121. isEdit
  2122. ? []
  2123. : [
  2124. {
  2125. required: true,
  2126. message: t('请上传密钥文件'),
  2127. },
  2128. ]
  2129. }
  2130. extraText={batchExtra}
  2131. />
  2132. )}
  2133. </>
  2134. ) : (
  2135. <Form.Input
  2136. field='key'
  2137. label={
  2138. isEdit
  2139. ? t('密钥(编辑模式下,保存的密钥不会显示)')
  2140. : t('密钥')
  2141. }
  2142. placeholder={
  2143. inputs.type === 33
  2144. ? inputs.aws_key_type === 'api_key'
  2145. ? t('请输入 API Key,格式:APIKey|Region')
  2146. : t(
  2147. '按照如下格式输入:AccessKey|SecretAccessKey|Region',
  2148. )
  2149. : t(type2secretPrompt(inputs.type))
  2150. }
  2151. rules={
  2152. isEdit
  2153. ? []
  2154. : [{ required: true, message: t('请输入密钥') }]
  2155. }
  2156. autoComplete='new-password'
  2157. onChange={(value) =>
  2158. handleInputChange('key', value)
  2159. }
  2160. extraText={
  2161. <div className='flex items-center gap-2'>
  2162. {isEdit &&
  2163. isMultiKeyChannel &&
  2164. keyMode === 'append' && (
  2165. <Text type='warning' size='small'>
  2166. {t(
  2167. '追加模式:新密钥将添加到现有密钥列表的末尾',
  2168. )}
  2169. </Text>
  2170. )}
  2171. {isEdit && (
  2172. <Button
  2173. size='small'
  2174. type='primary'
  2175. theme='outline'
  2176. onClick={handleShow2FAModal}
  2177. >
  2178. {t('查看密钥')}
  2179. </Button>
  2180. )}
  2181. {batchExtra}
  2182. </div>
  2183. }
  2184. showClear
  2185. />
  2186. )}
  2187. </>
  2188. )}
  2189. {isEdit && isMultiKeyChannel && (
  2190. <Form.Select
  2191. field='key_mode'
  2192. label={t('密钥更新模式')}
  2193. placeholder={t('请选择密钥更新模式')}
  2194. optionList={[
  2195. { label: t('追加到现有密钥'), value: 'append' },
  2196. { label: t('覆盖现有密钥'), value: 'replace' },
  2197. ]}
  2198. style={{ width: '100%' }}
  2199. value={keyMode}
  2200. onChange={(value) => setKeyMode(value)}
  2201. extraText={
  2202. <Text type='tertiary' size='small'>
  2203. {keyMode === 'replace'
  2204. ? t('覆盖模式:将完全替换现有的所有密钥')
  2205. : t('追加模式:将新密钥添加到现有密钥列表末尾')}
  2206. </Text>
  2207. }
  2208. />
  2209. )}
  2210. {batch && multiToSingle && (
  2211. <>
  2212. <Form.Select
  2213. field='multi_key_mode'
  2214. label={t('密钥聚合模式')}
  2215. placeholder={t('请选择多密钥使用策略')}
  2216. optionList={[
  2217. { label: t('随机'), value: 'random' },
  2218. { label: t('轮询'), value: 'polling' },
  2219. ]}
  2220. style={{ width: '100%' }}
  2221. value={inputs.multi_key_mode || 'random'}
  2222. onChange={(value) => {
  2223. setMultiKeyMode(value);
  2224. handleInputChange('multi_key_mode', value);
  2225. }}
  2226. />
  2227. {inputs.multi_key_mode === 'polling' && (
  2228. <Banner
  2229. type='warning'
  2230. description={t(
  2231. '轮询模式必须搭配Redis和内存缓存功能使用,否则性能将大幅降低,并且无法实现轮询功能',
  2232. )}
  2233. className='!rounded-lg mt-2'
  2234. />
  2235. )}
  2236. </>
  2237. )}
  2238. {inputs.type === 18 && (
  2239. <Form.Input
  2240. field='other'
  2241. label={t('模型版本')}
  2242. placeholder={
  2243. '请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1'
  2244. }
  2245. onChange={(value) => handleInputChange('other', value)}
  2246. showClear
  2247. />
  2248. )}
  2249. {inputs.type === 41 && (
  2250. <JSONEditor
  2251. key={`region-${isEdit ? channelId : 'new'}`}
  2252. field='other'
  2253. label={t('部署地区')}
  2254. placeholder={t(
  2255. '请输入部署地区,例如:us-central1\n支持使用模型映射格式\n{\n "default": "us-central1",\n "claude-3-5-sonnet-20240620": "europe-west1"\n}',
  2256. )}
  2257. value={inputs.other || ''}
  2258. onChange={(value) => handleInputChange('other', value)}
  2259. rules={[
  2260. { required: true, message: t('请填写部署地区') },
  2261. ]}
  2262. template={REGION_EXAMPLE}
  2263. templateLabel={t('填入模板')}
  2264. editorType='region'
  2265. formApi={formApiRef.current}
  2266. extraText={t('设置默认地区和特定模型的专用地区')}
  2267. />
  2268. )}
  2269. {inputs.type === 21 && (
  2270. <Form.Input
  2271. field='other'
  2272. label={t('知识库 ID')}
  2273. placeholder={'请输入知识库 ID,例如:123456'}
  2274. onChange={(value) => handleInputChange('other', value)}
  2275. showClear
  2276. />
  2277. )}
  2278. {inputs.type === 39 && (
  2279. <Form.Input
  2280. field='other'
  2281. label='Account ID'
  2282. placeholder={
  2283. '请输入Account ID,例如:d6b5da8hk1awo8nap34ube6gh'
  2284. }
  2285. onChange={(value) => handleInputChange('other', value)}
  2286. showClear
  2287. />
  2288. )}
  2289. {inputs.type === 49 && (
  2290. <Form.Input
  2291. field='other'
  2292. label={t('智能体ID')}
  2293. placeholder={'请输入智能体ID,例如:7342866812345'}
  2294. onChange={(value) => handleInputChange('other', value)}
  2295. showClear
  2296. />
  2297. )}
  2298. {inputs.type === 1 && (
  2299. <Form.Input
  2300. field='openai_organization'
  2301. label={t('组织')}
  2302. placeholder={t('请输入组织org-xxx')}
  2303. showClear
  2304. helpText={t('组织,不填则为默认组织')}
  2305. onChange={(value) =>
  2306. handleInputChange('openai_organization', value)
  2307. }
  2308. />
  2309. )}
  2310. </Card>
  2311. </div>
  2312. {/* API Configuration Card */}
  2313. {showApiConfigCard && (
  2314. <div ref={(el) => (formSectionRefs.current.apiConfig = el)}>
  2315. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2316. {/* Header: API Config */}
  2317. <div
  2318. className='flex items-center mb-2'
  2319. onClick={handleApiConfigSecretClick}
  2320. >
  2321. <Avatar
  2322. size='small'
  2323. color='green'
  2324. className='mr-2 shadow-md'
  2325. >
  2326. <IconGlobe size={16} />
  2327. </Avatar>
  2328. <div>
  2329. <Text className='text-lg font-medium'>
  2330. {t('API 配置')}
  2331. </Text>
  2332. <div className='text-xs text-gray-600'>
  2333. {t('API 地址和相关配置')}
  2334. </div>
  2335. </div>
  2336. </div>
  2337. {inputs.type === 40 && (
  2338. <Banner
  2339. type='info'
  2340. description={
  2341. <div>
  2342. <Text strong>{t('邀请链接')}:</Text>
  2343. <Text
  2344. link
  2345. underline
  2346. className='ml-2 cursor-pointer'
  2347. onClick={() =>
  2348. window.open(
  2349. 'https://cloud.siliconflow.cn/i/hij0YNTZ',
  2350. )
  2351. }
  2352. >
  2353. https://cloud.siliconflow.cn/i/hij0YNTZ
  2354. </Text>
  2355. </div>
  2356. }
  2357. className='!rounded-lg'
  2358. />
  2359. )}
  2360. {inputs.type === 3 && (
  2361. <>
  2362. <Banner
  2363. type='warning'
  2364. description={t(
  2365. '2025年5月10日后添加的渠道,不需要再在部署的时候移除模型名称中的"."',
  2366. )}
  2367. className='!rounded-lg'
  2368. />
  2369. <div>
  2370. <Form.Input
  2371. field='base_url'
  2372. label='AZURE_OPENAI_ENDPOINT'
  2373. placeholder={t(
  2374. '请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com',
  2375. )}
  2376. onChange={(value) =>
  2377. handleInputChange('base_url', value)
  2378. }
  2379. showClear
  2380. disabled={isIonetLocked}
  2381. />
  2382. </div>
  2383. <div>
  2384. <Form.Input
  2385. field='other'
  2386. label={t('默认 API 版本')}
  2387. placeholder={t(
  2388. '请输入默认 API 版本,例如:2025-04-01-preview',
  2389. )}
  2390. onChange={(value) =>
  2391. handleInputChange('other', value)
  2392. }
  2393. showClear
  2394. />
  2395. </div>
  2396. <div>
  2397. <Form.Input
  2398. field='azure_responses_version'
  2399. label={t(
  2400. '默认 Responses API 版本,为空则使用上方版本',
  2401. )}
  2402. placeholder={t('例如:preview')}
  2403. onChange={(value) =>
  2404. handleChannelOtherSettingsChange(
  2405. 'azure_responses_version',
  2406. value,
  2407. )
  2408. }
  2409. showClear
  2410. />
  2411. </div>
  2412. </>
  2413. )}
  2414. {inputs.type === 8 && (
  2415. <>
  2416. <Banner
  2417. type='warning'
  2418. description={t(
  2419. '如果你对接的是上游One API或者New API等转发项目,请使用OpenAI类型,不要使用此类型,除非你知道你在做什么。',
  2420. )}
  2421. className='!rounded-lg'
  2422. />
  2423. <div>
  2424. <Form.Input
  2425. field='base_url'
  2426. label={t('完整的 Base URL,支持变量{model}')}
  2427. placeholder={t(
  2428. '请输入完整的URL,例如:https://api.openai.com/v1/chat/completions',
  2429. )}
  2430. onChange={(value) =>
  2431. handleInputChange('base_url', value)
  2432. }
  2433. showClear
  2434. disabled={isIonetLocked}
  2435. />
  2436. </div>
  2437. </>
  2438. )}
  2439. {inputs.type === 37 && (
  2440. <Banner
  2441. type='warning'
  2442. description={t(
  2443. 'Dify渠道只适配chatflow和agent,并且agent不支持图片!',
  2444. )}
  2445. className='!rounded-lg'
  2446. />
  2447. )}
  2448. {inputs.type !== 3 &&
  2449. inputs.type !== 8 &&
  2450. inputs.type !== 22 &&
  2451. inputs.type !== 36 &&
  2452. (inputs.type !== 45 || doubaoApiEditUnlocked) && (
  2453. <div>
  2454. <Form.Input
  2455. field='base_url'
  2456. label={t('API地址')}
  2457. placeholder={t(
  2458. '此项可选,用于通过自定义API地址来进行 API 调用,末尾不要带/v1和/',
  2459. )}
  2460. onChange={(value) =>
  2461. handleInputChange('base_url', value)
  2462. }
  2463. showClear
  2464. disabled={isIonetLocked}
  2465. extraText={t(
  2466. '对于官方渠道,new-api已经内置地址,除非是第三方代理站点或者Azure的特殊接入地址,否则不需要填写',
  2467. )}
  2468. />
  2469. </div>
  2470. )}
  2471. {inputs.type === 22 && (
  2472. <div>
  2473. <Form.Input
  2474. field='base_url'
  2475. label={t('私有部署地址')}
  2476. placeholder={t(
  2477. '请输入私有部署地址,格式为:https://fastgpt.run/api/openapi',
  2478. )}
  2479. onChange={(value) =>
  2480. handleInputChange('base_url', value)
  2481. }
  2482. showClear
  2483. disabled={isIonetLocked}
  2484. />
  2485. </div>
  2486. )}
  2487. {inputs.type === 36 && (
  2488. <div>
  2489. <Form.Input
  2490. field='base_url'
  2491. label={t(
  2492. '注意非Chat API,请务必填写正确的API地址,否则可能导致无法使用',
  2493. )}
  2494. placeholder={t(
  2495. '请输入到 /suno 前的路径,通常就是域名,例如:https://api.example.com',
  2496. )}
  2497. onChange={(value) =>
  2498. handleInputChange('base_url', value)
  2499. }
  2500. showClear
  2501. disabled={isIonetLocked}
  2502. />
  2503. </div>
  2504. )}
  2505. {inputs.type === 45 && !doubaoApiEditUnlocked && (
  2506. <div>
  2507. <Form.Select
  2508. field='base_url'
  2509. label={t('API地址')}
  2510. placeholder={t('请选择API地址')}
  2511. onChange={(value) =>
  2512. handleInputChange('base_url', value)
  2513. }
  2514. optionList={[
  2515. {
  2516. value: 'https://ark.cn-beijing.volces.com',
  2517. label: 'https://ark.cn-beijing.volces.com',
  2518. },
  2519. {
  2520. value:
  2521. 'https://ark.ap-southeast.bytepluses.com',
  2522. label:
  2523. 'https://ark.ap-southeast.bytepluses.com',
  2524. },
  2525. {
  2526. value: 'doubao-coding-plan',
  2527. label: 'Doubao Coding Plan',
  2528. },
  2529. ]}
  2530. defaultValue='https://ark.cn-beijing.volces.com'
  2531. disabled={isIonetLocked}
  2532. />
  2533. </div>
  2534. )}
  2535. </Card>
  2536. </div>
  2537. )}
  2538. {/* Model Configuration Card */}
  2539. <div ref={(el) => (formSectionRefs.current.modelConfig = el)}>
  2540. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2541. {/* Header: Model Config */}
  2542. <div className='flex items-center mb-2'>
  2543. <Avatar
  2544. size='small'
  2545. color='purple'
  2546. className='mr-2 shadow-md'
  2547. >
  2548. <IconCode size={16} />
  2549. </Avatar>
  2550. <div>
  2551. <Text className='text-lg font-medium'>
  2552. {t('模型配置')}
  2553. </Text>
  2554. <div className='text-xs text-gray-600'>
  2555. {t('模型选择和映射设置')}
  2556. </div>
  2557. </div>
  2558. </div>
  2559. <Form.Select
  2560. field='models'
  2561. label={t('模型')}
  2562. placeholder={t('请选择该渠道所支持的模型')}
  2563. rules={[{ required: true, message: t('请选择模型') }]}
  2564. multiple
  2565. filter={selectFilter}
  2566. autoClearSearchValue={false}
  2567. searchPosition='dropdown'
  2568. optionList={modelOptions}
  2569. style={{ width: '100%' }}
  2570. onChange={(value) => handleInputChange('models', value)}
  2571. renderSelectedItem={(optionNode) => {
  2572. const modelName = String(optionNode?.value ?? '');
  2573. return {
  2574. isRenderInTag: true,
  2575. content: (
  2576. <span
  2577. className='cursor-pointer select-none'
  2578. role='button'
  2579. tabIndex={0}
  2580. title={t('点击复制模型名称')}
  2581. onClick={async (e) => {
  2582. e.stopPropagation();
  2583. const ok = await copy(modelName);
  2584. if (ok) {
  2585. showSuccess(
  2586. t('已复制:{{name}}', { name: modelName }),
  2587. );
  2588. } else {
  2589. showError(t('复制失败'));
  2590. }
  2591. }}
  2592. >
  2593. {optionNode.label || modelName}
  2594. </span>
  2595. ),
  2596. };
  2597. }}
  2598. extraText={
  2599. <Space wrap>
  2600. <Button
  2601. size='small'
  2602. type='primary'
  2603. onClick={() =>
  2604. handleInputChange('models', basicModels)
  2605. }
  2606. >
  2607. {t('填入相关模型')}
  2608. </Button>
  2609. <Button
  2610. size='small'
  2611. type='secondary'
  2612. onClick={() =>
  2613. handleInputChange('models', fullModels)
  2614. }
  2615. >
  2616. {t('填入所有模型')}
  2617. </Button>
  2618. {MODEL_FETCHABLE_TYPES.has(inputs.type) && (
  2619. <Button
  2620. size='small'
  2621. type='tertiary'
  2622. onClick={() => fetchUpstreamModelList('models')}
  2623. >
  2624. {t('获取模型列表')}
  2625. </Button>
  2626. )}
  2627. {inputs.type === 4 && isEdit && (
  2628. <Button
  2629. size='small'
  2630. type='primary'
  2631. theme='light'
  2632. onClick={() => setOllamaModalVisible(true)}
  2633. >
  2634. {t('Ollama 模型管理')}
  2635. </Button>
  2636. )}
  2637. <Button
  2638. size='small'
  2639. type='warning'
  2640. onClick={() => handleInputChange('models', [])}
  2641. >
  2642. {t('清除所有模型')}
  2643. </Button>
  2644. <Button
  2645. size='small'
  2646. type='tertiary'
  2647. onClick={() => {
  2648. if (inputs.models.length === 0) {
  2649. showInfo(t('没有模型可以复制'));
  2650. return;
  2651. }
  2652. try {
  2653. copy(inputs.models.join(','));
  2654. showSuccess(t('模型列表已复制到剪贴板'));
  2655. } catch (error) {
  2656. showError(t('复制失败'));
  2657. }
  2658. }}
  2659. >
  2660. {t('复制所有模型')}
  2661. </Button>
  2662. {modelGroups &&
  2663. modelGroups.length > 0 &&
  2664. modelGroups.map((group) => (
  2665. <Button
  2666. key={group.id}
  2667. size='small'
  2668. type='primary'
  2669. onClick={() => {
  2670. let items = [];
  2671. try {
  2672. if (Array.isArray(group.items)) {
  2673. items = group.items;
  2674. } else if (
  2675. typeof group.items === 'string'
  2676. ) {
  2677. const parsed = JSON.parse(
  2678. group.items || '[]',
  2679. );
  2680. if (Array.isArray(parsed)) items = parsed;
  2681. }
  2682. } catch {}
  2683. const current =
  2684. formApiRef.current?.getValue('models') ||
  2685. inputs.models ||
  2686. [];
  2687. const merged = Array.from(
  2688. new Set(
  2689. [...current, ...items]
  2690. .map((m) => (m || '').trim())
  2691. .filter(Boolean),
  2692. ),
  2693. );
  2694. handleInputChange('models', merged);
  2695. }}
  2696. >
  2697. {group.name}
  2698. </Button>
  2699. ))}
  2700. </Space>
  2701. }
  2702. />
  2703. <Form.Input
  2704. field='custom_model'
  2705. label={t('自定义模型名称')}
  2706. placeholder={t('输入自定义模型名称')}
  2707. onChange={(value) => setCustomModel(value.trim())}
  2708. value={customModel}
  2709. suffix={
  2710. <Button
  2711. size='small'
  2712. type='primary'
  2713. onClick={addCustomModels}
  2714. >
  2715. {t('填入')}
  2716. </Button>
  2717. }
  2718. />
  2719. <Form.Input
  2720. field='test_model'
  2721. label={t('默认测试模型')}
  2722. placeholder={t('不填则为模型列表第一个')}
  2723. onChange={(value) =>
  2724. handleInputChange('test_model', value)
  2725. }
  2726. showClear
  2727. />
  2728. <JSONEditor
  2729. key={`model_mapping-${isEdit ? channelId : 'new'}`}
  2730. field='model_mapping'
  2731. label={t('模型重定向')}
  2732. placeholder={
  2733. t(
  2734. '此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:',
  2735. ) +
  2736. `\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`
  2737. }
  2738. value={inputs.model_mapping || ''}
  2739. onChange={(value) =>
  2740. handleInputChange('model_mapping', value)
  2741. }
  2742. template={MODEL_MAPPING_EXAMPLE}
  2743. templateLabel={t('填入模板')}
  2744. editorType='keyValue'
  2745. formApi={formApiRef.current}
  2746. renderStringValueSuffix={({ pairKey, value }) => {
  2747. if (!MODEL_FETCHABLE_TYPES.has(inputs.type)) {
  2748. return null;
  2749. }
  2750. const disabled = !String(pairKey ?? '').trim();
  2751. return (
  2752. <Tooltip content={t('选择模型')}>
  2753. <Button
  2754. type='tertiary'
  2755. theme='borderless'
  2756. size='small'
  2757. icon={<IconSearch size={14} />}
  2758. disabled={disabled}
  2759. onClick={(e) => {
  2760. e.stopPropagation();
  2761. openModelMappingValueModal({ pairKey, value });
  2762. }}
  2763. />
  2764. </Tooltip>
  2765. );
  2766. }}
  2767. extraText={t(
  2768. '键为请求中的模型名称,值为要替换的模型名称',
  2769. )}
  2770. />
  2771. </Card>
  2772. </div>
  2773. {/* Advanced Settings Card */}
  2774. <div
  2775. ref={(el) => (formSectionRefs.current.advancedSettings = el)}
  2776. >
  2777. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2778. {/* Header: Advanced Settings */}
  2779. <div className='flex items-center mb-2'>
  2780. <Avatar
  2781. size='small'
  2782. color='orange'
  2783. className='mr-2 shadow-md'
  2784. >
  2785. <IconSetting size={16} />
  2786. </Avatar>
  2787. <div>
  2788. <Text className='text-lg font-medium'>
  2789. {t('高级设置')}
  2790. </Text>
  2791. <div className='text-xs text-gray-600'>
  2792. {t('渠道的高级配置选项')}
  2793. </div>
  2794. </div>
  2795. </div>
  2796. <Form.Select
  2797. field='groups'
  2798. label={t('分组')}
  2799. placeholder={t('请选择可以使用该渠道的分组')}
  2800. multiple
  2801. allowAdditions
  2802. additionLabel={t(
  2803. '请在系统设置页面编辑分组倍率以添加新的分组:',
  2804. )}
  2805. optionList={groupOptions}
  2806. style={{ width: '100%' }}
  2807. onChange={(value) => handleInputChange('groups', value)}
  2808. />
  2809. <Form.Input
  2810. field='tag'
  2811. label={t('渠道标签')}
  2812. placeholder={t('渠道标签')}
  2813. showClear
  2814. onChange={(value) => handleInputChange('tag', value)}
  2815. />
  2816. <Form.TextArea
  2817. field='remark'
  2818. label={t('备注')}
  2819. placeholder={t('请输入备注(仅管理员可见)')}
  2820. maxLength={255}
  2821. showClear
  2822. onChange={(value) => handleInputChange('remark', value)}
  2823. />
  2824. <Row gutter={12}>
  2825. <Col span={12}>
  2826. <Form.InputNumber
  2827. field='priority'
  2828. label={t('渠道优先级')}
  2829. placeholder={t('渠道优先级')}
  2830. min={0}
  2831. onNumberChange={(value) =>
  2832. handleInputChange('priority', value)
  2833. }
  2834. style={{ width: '100%' }}
  2835. />
  2836. </Col>
  2837. <Col span={12}>
  2838. <Form.InputNumber
  2839. field='weight'
  2840. label={t('渠道权重')}
  2841. placeholder={t('渠道权重')}
  2842. min={0}
  2843. onNumberChange={(value) =>
  2844. handleInputChange('weight', value)
  2845. }
  2846. style={{ width: '100%' }}
  2847. />
  2848. </Col>
  2849. </Row>
  2850. <Form.Switch
  2851. field='auto_ban'
  2852. label={t('是否自动禁用')}
  2853. checkedText={t('开')}
  2854. uncheckedText={t('关')}
  2855. onChange={(value) => setAutoBan(value)}
  2856. extraText={t(
  2857. '仅当自动禁用开启时有效,关闭后不会自动禁用该渠道',
  2858. )}
  2859. initValue={autoBan}
  2860. />
  2861. <Form.TextArea
  2862. field='param_override'
  2863. label={t('参数覆盖')}
  2864. placeholder={
  2865. t(
  2866. '此项可选,用于覆盖请求参数。不支持覆盖 stream 参数',
  2867. ) +
  2868. '\n' +
  2869. t('旧格式(直接覆盖):') +
  2870. '\n{\n "temperature": 0,\n "max_tokens": 1000\n}' +
  2871. '\n\n' +
  2872. t('新格式(支持条件判断与json自定义):') +
  2873. '\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}'
  2874. }
  2875. autosize
  2876. onChange={(value) =>
  2877. handleInputChange('param_override', value)
  2878. }
  2879. extraText={
  2880. <div className='flex gap-2 flex-wrap'>
  2881. <Text
  2882. className='!text-semi-color-primary cursor-pointer'
  2883. onClick={() =>
  2884. handleInputChange(
  2885. 'param_override',
  2886. JSON.stringify({ temperature: 0 }, null, 2),
  2887. )
  2888. }
  2889. >
  2890. {t('旧格式模板')}
  2891. </Text>
  2892. <Text
  2893. className='!text-semi-color-primary cursor-pointer'
  2894. onClick={() =>
  2895. handleInputChange(
  2896. 'param_override',
  2897. JSON.stringify(
  2898. {
  2899. operations: [
  2900. {
  2901. path: 'temperature',
  2902. mode: 'set',
  2903. value: 0.7,
  2904. conditions: [
  2905. {
  2906. path: 'model',
  2907. mode: 'prefix',
  2908. value: 'gpt',
  2909. },
  2910. ],
  2911. logic: 'AND',
  2912. },
  2913. ],
  2914. },
  2915. null,
  2916. 2,
  2917. ),
  2918. )
  2919. }
  2920. >
  2921. {t('新格式模板')}
  2922. </Text>
  2923. <Text
  2924. className='!text-semi-color-primary cursor-pointer'
  2925. onClick={() => formatJsonField('param_override')}
  2926. >
  2927. {t('格式化')}
  2928. </Text>
  2929. </div>
  2930. }
  2931. showClear
  2932. />
  2933. <Form.TextArea
  2934. field='header_override'
  2935. label={t('请求头覆盖')}
  2936. placeholder={
  2937. t('此项可选,用于覆盖请求头参数') +
  2938. '\n' +
  2939. t('格式示例:') +
  2940. '\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 "Authorization": "Bearer {api_key}"\n}'
  2941. }
  2942. autosize
  2943. onChange={(value) =>
  2944. handleInputChange('header_override', value)
  2945. }
  2946. extraText={
  2947. <div className='flex flex-col gap-1'>
  2948. <div className='flex gap-2 flex-wrap items-center'>
  2949. <Text
  2950. className='!text-semi-color-primary cursor-pointer'
  2951. onClick={() =>
  2952. handleInputChange(
  2953. 'header_override',
  2954. JSON.stringify(
  2955. {
  2956. 'User-Agent':
  2957. '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',
  2958. Authorization: 'Bearer{api_key}',
  2959. },
  2960. null,
  2961. 2,
  2962. ),
  2963. )
  2964. }
  2965. >
  2966. {t('填入模板')}
  2967. </Text>
  2968. <Text
  2969. className='!text-semi-color-primary cursor-pointer'
  2970. onClick={() => formatJsonField('header_override')}
  2971. >
  2972. {t('格式化')}
  2973. </Text>
  2974. </div>
  2975. <div>
  2976. <Text type='tertiary' size='small'>
  2977. {t('支持变量:')}
  2978. </Text>
  2979. <div className='text-xs text-tertiary ml-2'>
  2980. <div>
  2981. {t('渠道密钥')}: {'{api_key}'}
  2982. </div>
  2983. </div>
  2984. </div>
  2985. </div>
  2986. }
  2987. showClear
  2988. />
  2989. <JSONEditor
  2990. key={`status_code_mapping-${isEdit ? channelId : 'new'}`}
  2991. field='status_code_mapping'
  2992. label={t('状态码复写')}
  2993. placeholder={
  2994. t(
  2995. '此项可选,用于复写返回的状态码,仅影响本地判断,不修改返回到上游的状态码,比如将claude渠道的400错误复写为500(用于重试),请勿滥用该功能,例如:',
  2996. ) +
  2997. '\n' +
  2998. JSON.stringify(STATUS_CODE_MAPPING_EXAMPLE, null, 2)
  2999. }
  3000. value={inputs.status_code_mapping || ''}
  3001. onChange={(value) =>
  3002. handleInputChange('status_code_mapping', value)
  3003. }
  3004. template={STATUS_CODE_MAPPING_EXAMPLE}
  3005. templateLabel={t('填入模板')}
  3006. editorType='keyValue'
  3007. formApi={formApiRef.current}
  3008. extraText={t(
  3009. '键为原状态码,值为要复写的状态码,仅影响本地判断',
  3010. )}
  3011. />
  3012. {/* 字段透传控制 - OpenAI 渠道 */}
  3013. {inputs.type === 1 && (
  3014. <>
  3015. <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
  3016. {t('字段透传控制')}
  3017. </div>
  3018. <Form.Switch
  3019. field='allow_service_tier'
  3020. label={t('允许 service_tier 透传')}
  3021. checkedText={t('开')}
  3022. uncheckedText={t('关')}
  3023. onChange={(value) =>
  3024. handleChannelOtherSettingsChange(
  3025. 'allow_service_tier',
  3026. value,
  3027. )
  3028. }
  3029. extraText={t(
  3030. 'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
  3031. )}
  3032. />
  3033. <Form.Switch
  3034. field='disable_store'
  3035. label={t('禁用 store 透传')}
  3036. checkedText={t('开')}
  3037. uncheckedText={t('关')}
  3038. onChange={(value) =>
  3039. handleChannelOtherSettingsChange(
  3040. 'disable_store',
  3041. value,
  3042. )
  3043. }
  3044. extraText={t(
  3045. 'store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用',
  3046. )}
  3047. />
  3048. <Form.Switch
  3049. field='allow_safety_identifier'
  3050. label={t('允许 safety_identifier 透传')}
  3051. checkedText={t('开')}
  3052. uncheckedText={t('关')}
  3053. onChange={(value) =>
  3054. handleChannelOtherSettingsChange(
  3055. 'allow_safety_identifier',
  3056. value,
  3057. )
  3058. }
  3059. extraText={t(
  3060. 'safety_identifier 字段用于帮助 OpenAI 识别可能违反使用政策的应用程序用户。默认关闭以保护用户隐私',
  3061. )}
  3062. />
  3063. </>
  3064. )}
  3065. {/* 字段透传控制 - Claude 渠道 */}
  3066. {inputs.type === 14 && (
  3067. <>
  3068. <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
  3069. {t('字段透传控制')}
  3070. </div>
  3071. <Form.Switch
  3072. field='allow_service_tier'
  3073. label={t('允许 service_tier 透传')}
  3074. checkedText={t('开')}
  3075. uncheckedText={t('关')}
  3076. onChange={(value) =>
  3077. handleChannelOtherSettingsChange(
  3078. 'allow_service_tier',
  3079. value,
  3080. )
  3081. }
  3082. extraText={t(
  3083. 'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
  3084. )}
  3085. />
  3086. </>
  3087. )}
  3088. </Card>
  3089. </div>
  3090. {/* Channel Extra Settings Card */}
  3091. <div
  3092. ref={(el) =>
  3093. (formSectionRefs.current.channelExtraSettings = el)
  3094. }
  3095. >
  3096. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  3097. {/* Header: Channel Extra Settings */}
  3098. <div className='flex items-center mb-2'>
  3099. <Avatar
  3100. size='small'
  3101. color='violet'
  3102. className='mr-2 shadow-md'
  3103. >
  3104. <IconBolt size={16} />
  3105. </Avatar>
  3106. <div>
  3107. <Text className='text-lg font-medium'>
  3108. {t('渠道额外设置')}
  3109. </Text>
  3110. </div>
  3111. </div>
  3112. {inputs.type === 1 && (
  3113. <Form.Switch
  3114. field='force_format'
  3115. label={t('强制格式化')}
  3116. checkedText={t('开')}
  3117. uncheckedText={t('关')}
  3118. onChange={(value) =>
  3119. handleChannelSettingsChange('force_format', value)
  3120. }
  3121. extraText={t(
  3122. '强制将响应格式化为 OpenAI 标准格式(只适用于OpenAI渠道类型)',
  3123. )}
  3124. />
  3125. )}
  3126. <Form.Switch
  3127. field='thinking_to_content'
  3128. label={t('思考内容转换')}
  3129. checkedText={t('开')}
  3130. uncheckedText={t('关')}
  3131. onChange={(value) =>
  3132. handleChannelSettingsChange(
  3133. 'thinking_to_content',
  3134. value,
  3135. )
  3136. }
  3137. extraText={t(
  3138. '将 reasoning_content 转换为 <think> 标签拼接到内容中',
  3139. )}
  3140. />
  3141. <Form.Switch
  3142. field='pass_through_body_enabled'
  3143. label={t('透传请求体')}
  3144. checkedText={t('开')}
  3145. uncheckedText={t('关')}
  3146. onChange={(value) =>
  3147. handleChannelSettingsChange(
  3148. 'pass_through_body_enabled',
  3149. value,
  3150. )
  3151. }
  3152. extraText={t('启用请求体透传功能')}
  3153. />
  3154. <Form.Input
  3155. field='proxy'
  3156. label={t('代理地址')}
  3157. placeholder={t('例如: socks5://user:pass@host:port')}
  3158. onChange={(value) =>
  3159. handleChannelSettingsChange('proxy', value)
  3160. }
  3161. showClear
  3162. extraText={t('用于配置网络代理,支持 socks5 协议')}
  3163. />
  3164. <Form.TextArea
  3165. field='system_prompt'
  3166. label={t('系统提示词')}
  3167. placeholder={t(
  3168. '输入系统提示词,用户的系统提示词将优先于此设置',
  3169. )}
  3170. onChange={(value) =>
  3171. handleChannelSettingsChange('system_prompt', value)
  3172. }
  3173. autosize
  3174. showClear
  3175. extraText={t(
  3176. '用户优先:如果用户在请求中指定了系统提示词,将优先使用用户的设置',
  3177. )}
  3178. />
  3179. <Form.Switch
  3180. field='system_prompt_override'
  3181. label={t('系统提示词拼接')}
  3182. checkedText={t('开')}
  3183. uncheckedText={t('关')}
  3184. onChange={(value) =>
  3185. handleChannelSettingsChange(
  3186. 'system_prompt_override',
  3187. value,
  3188. )
  3189. }
  3190. extraText={t(
  3191. '如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
  3192. )}
  3193. />
  3194. </Card>
  3195. </div>
  3196. </div>
  3197. </Spin>
  3198. )}
  3199. </Form>
  3200. <ImagePreview
  3201. src={modalImageUrl}
  3202. visible={isModalOpenurl}
  3203. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  3204. />
  3205. </SideSheet>
  3206. {/* 使用通用安全验证模态框 */}
  3207. <SecureVerificationModal
  3208. visible={isModalVisible}
  3209. verificationMethods={verificationMethods}
  3210. verificationState={verificationState}
  3211. onVerify={executeVerification}
  3212. onCancel={cancelVerification}
  3213. onCodeChange={setVerificationCode}
  3214. onMethodSwitch={switchVerificationMethod}
  3215. title={verificationState.title}
  3216. description={verificationState.description}
  3217. />
  3218. {/* 使用ChannelKeyDisplay组件显示密钥 */}
  3219. <Modal
  3220. title={
  3221. <div className='flex items-center'>
  3222. <div className='w-8 h-8 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center mr-3'>
  3223. <svg
  3224. className='w-4 h-4 text-green-600 dark:text-green-400'
  3225. fill='currentColor'
  3226. viewBox='0 0 20 20'
  3227. >
  3228. <path
  3229. fillRule='evenodd'
  3230. 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'
  3231. clipRule='evenodd'
  3232. />
  3233. </svg>
  3234. </div>
  3235. {t('渠道密钥信息')}
  3236. </div>
  3237. }
  3238. visible={keyDisplayState.showModal}
  3239. onCancel={resetKeyDisplayState}
  3240. footer={
  3241. <Button type='primary' onClick={resetKeyDisplayState}>
  3242. {t('完成')}
  3243. </Button>
  3244. }
  3245. width={700}
  3246. style={{ maxWidth: '90vw' }}
  3247. >
  3248. <ChannelKeyDisplay
  3249. keyData={keyDisplayState.keyData}
  3250. showSuccessIcon={true}
  3251. successText={t('密钥获取成功')}
  3252. showWarning={true}
  3253. warningText={t(
  3254. '请妥善保管密钥信息,不要泄露给他人。如有安全疑虑,请及时更换密钥。',
  3255. )}
  3256. />
  3257. </Modal>
  3258. <ModelSelectModal
  3259. visible={modelModalVisible}
  3260. models={fetchedModels}
  3261. selected={inputs.models}
  3262. redirectModels={redirectModelList}
  3263. onConfirm={(selectedModels) => {
  3264. handleInputChange('models', selectedModels);
  3265. showSuccess(t('模型列表已更新'));
  3266. setModelModalVisible(false);
  3267. }}
  3268. onCancel={() => setModelModalVisible(false)}
  3269. />
  3270. <SingleModelSelectModal
  3271. visible={modelMappingValueModalVisible}
  3272. models={modelMappingValueModalModels}
  3273. selected={modelMappingValueSelected}
  3274. onConfirm={(selectedModel) => {
  3275. const modelName = String(selectedModel ?? '').trim();
  3276. if (!modelName) {
  3277. showError(t('请先选择模型!'));
  3278. return;
  3279. }
  3280. const mappingKey = String(modelMappingValueKey ?? '').trim();
  3281. if (!mappingKey) {
  3282. setModelMappingValueModalVisible(false);
  3283. return;
  3284. }
  3285. let parsed = {};
  3286. const currentMapping = inputs.model_mapping;
  3287. if (typeof currentMapping === 'string' && currentMapping.trim()) {
  3288. try {
  3289. parsed = JSON.parse(currentMapping);
  3290. } catch (error) {
  3291. parsed = {};
  3292. }
  3293. } else if (
  3294. currentMapping &&
  3295. typeof currentMapping === 'object' &&
  3296. !Array.isArray(currentMapping)
  3297. ) {
  3298. parsed = currentMapping;
  3299. }
  3300. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
  3301. parsed = {};
  3302. }
  3303. parsed[mappingKey] = modelName;
  3304. const nextMapping = JSON.stringify(parsed, null, 2);
  3305. handleInputChange('model_mapping', nextMapping);
  3306. if (formApiRef.current) {
  3307. formApiRef.current.setValue('model_mapping', nextMapping);
  3308. }
  3309. setModelMappingValueModalVisible(false);
  3310. }}
  3311. onCancel={() => setModelMappingValueModalVisible(false)}
  3312. />
  3313. <OllamaModelModal
  3314. visible={ollamaModalVisible}
  3315. onCancel={() => setOllamaModalVisible(false)}
  3316. channelId={channelId}
  3317. channelInfo={inputs}
  3318. onModelsUpdate={(options = {}) => {
  3319. // 当模型更新后,重新获取模型列表以更新表单
  3320. fetchUpstreamModelList('models', { silent: !!options.silent });
  3321. }}
  3322. onApplyModels={({ mode, modelIds } = {}) => {
  3323. if (!Array.isArray(modelIds) || modelIds.length === 0) {
  3324. return;
  3325. }
  3326. const existingModels = Array.isArray(inputs.models)
  3327. ? inputs.models.map(String)
  3328. : [];
  3329. const incoming = modelIds.map(String);
  3330. const nextModels = Array.from(
  3331. new Set([...existingModels, ...incoming]),
  3332. );
  3333. handleInputChange('models', nextModels);
  3334. if (formApiRef.current) {
  3335. formApiRef.current.setValue('models', nextModels);
  3336. }
  3337. showSuccess(t('模型列表已追加更新'));
  3338. }}
  3339. />
  3340. </>
  3341. );
  3342. };
  3343. export default EditChannelModal;