EditChannelModal.jsx 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523
  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. : [{ required: true, message: t('请输入密钥') }]
  1913. }
  1914. autoComplete='new-password'
  1915. onChange={(value) => handleInputChange('key', value)}
  1916. disabled={isIonetLocked}
  1917. extraText={
  1918. <div className='flex flex-col gap-2'>
  1919. <Text type='tertiary' size='small'>
  1920. {t(
  1921. '仅支持 JSON 对象,必须包含 access_token 与 account_id',
  1922. )}
  1923. </Text>
  1924. <Space wrap spacing='tight'>
  1925. <Button
  1926. size='small'
  1927. type='primary'
  1928. theme='outline'
  1929. onClick={() =>
  1930. setCodexOAuthModalVisible(true)
  1931. }
  1932. disabled={isIonetLocked}
  1933. >
  1934. {t('Codex 授权')}
  1935. </Button>
  1936. {isEdit && (
  1937. <Button
  1938. size='small'
  1939. type='primary'
  1940. theme='outline'
  1941. onClick={handleRefreshCodexCredential}
  1942. loading={codexCredentialRefreshing}
  1943. disabled={isIonetLocked}
  1944. >
  1945. {t('刷新凭证')}
  1946. </Button>
  1947. )}
  1948. <Button
  1949. size='small'
  1950. type='primary'
  1951. theme='outline'
  1952. onClick={() => formatJsonField('key')}
  1953. disabled={isIonetLocked}
  1954. >
  1955. {t('格式化')}
  1956. </Button>
  1957. {isEdit && (
  1958. <Button
  1959. size='small'
  1960. type='primary'
  1961. theme='outline'
  1962. onClick={handleShow2FAModal}
  1963. disabled={isIonetLocked}
  1964. >
  1965. {t('查看密钥')}
  1966. </Button>
  1967. )}
  1968. {batchExtra}
  1969. </Space>
  1970. </div>
  1971. }
  1972. autosize
  1973. showClear
  1974. />
  1975. <CodexOAuthModal
  1976. visible={codexOAuthModalVisible}
  1977. onCancel={() => setCodexOAuthModalVisible(false)}
  1978. onSuccess={handleCodexOAuthGenerated}
  1979. />
  1980. </>
  1981. ) : inputs.type === 41 &&
  1982. (inputs.vertex_key_type || 'json') === 'json' ? (
  1983. <>
  1984. {!batch && (
  1985. <div className='flex items-center justify-between mb-3'>
  1986. <Text className='text-sm font-medium'>
  1987. {t('密钥输入方式')}
  1988. </Text>
  1989. <Space>
  1990. <Button
  1991. size='small'
  1992. type={
  1993. !useManualInput ? 'primary' : 'tertiary'
  1994. }
  1995. onClick={() => {
  1996. setUseManualInput(false);
  1997. // 切换到文件上传模式时清空手动输入的密钥
  1998. if (formApiRef.current) {
  1999. formApiRef.current.setValue('key', '');
  2000. }
  2001. handleInputChange('key', '');
  2002. }}
  2003. >
  2004. {t('文件上传')}
  2005. </Button>
  2006. <Button
  2007. size='small'
  2008. type={useManualInput ? 'primary' : 'tertiary'}
  2009. onClick={() => {
  2010. setUseManualInput(true);
  2011. // 切换到手动输入模式时清空文件上传相关状态
  2012. setVertexKeys([]);
  2013. setVertexFileList([]);
  2014. if (formApiRef.current) {
  2015. formApiRef.current.setValue(
  2016. 'vertex_files',
  2017. [],
  2018. );
  2019. }
  2020. setInputs((prev) => ({
  2021. ...prev,
  2022. vertex_files: [],
  2023. }));
  2024. }}
  2025. >
  2026. {t('手动输入')}
  2027. </Button>
  2028. </Space>
  2029. </div>
  2030. )}
  2031. {batch && (
  2032. <Banner
  2033. type='info'
  2034. description={t(
  2035. '批量创建模式下仅支持文件上传,不支持手动输入',
  2036. )}
  2037. className='!rounded-lg mb-3'
  2038. />
  2039. )}
  2040. {useManualInput && !batch ? (
  2041. <Form.TextArea
  2042. field='key'
  2043. label={
  2044. isEdit
  2045. ? t(
  2046. '密钥(编辑模式下,保存的密钥不会显示)',
  2047. )
  2048. : t('密钥')
  2049. }
  2050. placeholder={t(
  2051. '请输入 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}',
  2052. )}
  2053. rules={
  2054. isEdit
  2055. ? []
  2056. : [
  2057. {
  2058. required: true,
  2059. message: t('请输入密钥'),
  2060. },
  2061. ]
  2062. }
  2063. autoComplete='new-password'
  2064. onChange={(value) =>
  2065. handleInputChange('key', value)
  2066. }
  2067. extraText={
  2068. <div className='flex items-center gap-2'>
  2069. <Text type='tertiary' size='small'>
  2070. {t('请输入完整的 JSON 格式密钥内容')}
  2071. </Text>
  2072. {isEdit &&
  2073. isMultiKeyChannel &&
  2074. keyMode === 'append' && (
  2075. <Text type='warning' size='small'>
  2076. {t(
  2077. '追加模式:新密钥将添加到现有密钥列表的末尾',
  2078. )}
  2079. </Text>
  2080. )}
  2081. {isEdit && (
  2082. <Button
  2083. size='small'
  2084. type='primary'
  2085. theme='outline'
  2086. onClick={handleShow2FAModal}
  2087. >
  2088. {t('查看密钥')}
  2089. </Button>
  2090. )}
  2091. {batchExtra}
  2092. </div>
  2093. }
  2094. autosize
  2095. showClear
  2096. />
  2097. ) : (
  2098. <Form.Upload
  2099. field='vertex_files'
  2100. label={t('密钥文件 (.json)')}
  2101. accept='.json'
  2102. draggable
  2103. dragIcon={<IconBolt />}
  2104. dragMainText={t('点击上传文件或拖拽文件到这里')}
  2105. dragSubText={t('仅支持 JSON 文件')}
  2106. style={{ marginTop: 10 }}
  2107. uploadTrigger='custom'
  2108. beforeUpload={() => false}
  2109. onChange={handleVertexUploadChange}
  2110. fileList={vertexFileList}
  2111. rules={
  2112. isEdit
  2113. ? []
  2114. : [
  2115. {
  2116. required: true,
  2117. message: t('请上传密钥文件'),
  2118. },
  2119. ]
  2120. }
  2121. extraText={batchExtra}
  2122. />
  2123. )}
  2124. </>
  2125. ) : (
  2126. <Form.Input
  2127. field='key'
  2128. label={
  2129. isEdit
  2130. ? t('密钥(编辑模式下,保存的密钥不会显示)')
  2131. : t('密钥')
  2132. }
  2133. placeholder={
  2134. inputs.type === 33
  2135. ? inputs.aws_key_type === 'api_key'
  2136. ? t('请输入 API Key,格式:APIKey|Region')
  2137. : t(
  2138. '按照如下格式输入:AccessKey|SecretAccessKey|Region',
  2139. )
  2140. : t(type2secretPrompt(inputs.type))
  2141. }
  2142. rules={
  2143. isEdit
  2144. ? []
  2145. : [{ required: true, message: t('请输入密钥') }]
  2146. }
  2147. autoComplete='new-password'
  2148. onChange={(value) =>
  2149. handleInputChange('key', value)
  2150. }
  2151. extraText={
  2152. <div className='flex items-center gap-2'>
  2153. {isEdit &&
  2154. isMultiKeyChannel &&
  2155. keyMode === 'append' && (
  2156. <Text type='warning' size='small'>
  2157. {t(
  2158. '追加模式:新密钥将添加到现有密钥列表的末尾',
  2159. )}
  2160. </Text>
  2161. )}
  2162. {isEdit && (
  2163. <Button
  2164. size='small'
  2165. type='primary'
  2166. theme='outline'
  2167. onClick={handleShow2FAModal}
  2168. >
  2169. {t('查看密钥')}
  2170. </Button>
  2171. )}
  2172. {batchExtra}
  2173. </div>
  2174. }
  2175. showClear
  2176. />
  2177. )}
  2178. </>
  2179. )}
  2180. {isEdit && isMultiKeyChannel && (
  2181. <Form.Select
  2182. field='key_mode'
  2183. label={t('密钥更新模式')}
  2184. placeholder={t('请选择密钥更新模式')}
  2185. optionList={[
  2186. { label: t('追加到现有密钥'), value: 'append' },
  2187. { label: t('覆盖现有密钥'), value: 'replace' },
  2188. ]}
  2189. style={{ width: '100%' }}
  2190. value={keyMode}
  2191. onChange={(value) => setKeyMode(value)}
  2192. extraText={
  2193. <Text type='tertiary' size='small'>
  2194. {keyMode === 'replace'
  2195. ? t('覆盖模式:将完全替换现有的所有密钥')
  2196. : t('追加模式:将新密钥添加到现有密钥列表末尾')}
  2197. </Text>
  2198. }
  2199. />
  2200. )}
  2201. {batch && multiToSingle && (
  2202. <>
  2203. <Form.Select
  2204. field='multi_key_mode'
  2205. label={t('密钥聚合模式')}
  2206. placeholder={t('请选择多密钥使用策略')}
  2207. optionList={[
  2208. { label: t('随机'), value: 'random' },
  2209. { label: t('轮询'), value: 'polling' },
  2210. ]}
  2211. style={{ width: '100%' }}
  2212. value={inputs.multi_key_mode || 'random'}
  2213. onChange={(value) => {
  2214. setMultiKeyMode(value);
  2215. handleInputChange('multi_key_mode', value);
  2216. }}
  2217. />
  2218. {inputs.multi_key_mode === 'polling' && (
  2219. <Banner
  2220. type='warning'
  2221. description={t(
  2222. '轮询模式必须搭配Redis和内存缓存功能使用,否则性能将大幅降低,并且无法实现轮询功能',
  2223. )}
  2224. className='!rounded-lg mt-2'
  2225. />
  2226. )}
  2227. </>
  2228. )}
  2229. {inputs.type === 18 && (
  2230. <Form.Input
  2231. field='other'
  2232. label={t('模型版本')}
  2233. placeholder={
  2234. '请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1'
  2235. }
  2236. onChange={(value) => handleInputChange('other', value)}
  2237. showClear
  2238. />
  2239. )}
  2240. {inputs.type === 41 && (
  2241. <JSONEditor
  2242. key={`region-${isEdit ? channelId : 'new'}`}
  2243. field='other'
  2244. label={t('部署地区')}
  2245. placeholder={t(
  2246. '请输入部署地区,例如:us-central1\n支持使用模型映射格式\n{\n "default": "us-central1",\n "claude-3-5-sonnet-20240620": "europe-west1"\n}',
  2247. )}
  2248. value={inputs.other || ''}
  2249. onChange={(value) => handleInputChange('other', value)}
  2250. rules={[
  2251. { required: true, message: t('请填写部署地区') },
  2252. ]}
  2253. template={REGION_EXAMPLE}
  2254. templateLabel={t('填入模板')}
  2255. editorType='region'
  2256. formApi={formApiRef.current}
  2257. extraText={t('设置默认地区和特定模型的专用地区')}
  2258. />
  2259. )}
  2260. {inputs.type === 21 && (
  2261. <Form.Input
  2262. field='other'
  2263. label={t('知识库 ID')}
  2264. placeholder={'请输入知识库 ID,例如:123456'}
  2265. onChange={(value) => handleInputChange('other', value)}
  2266. showClear
  2267. />
  2268. )}
  2269. {inputs.type === 39 && (
  2270. <Form.Input
  2271. field='other'
  2272. label='Account ID'
  2273. placeholder={
  2274. '请输入Account ID,例如:d6b5da8hk1awo8nap34ube6gh'
  2275. }
  2276. onChange={(value) => handleInputChange('other', value)}
  2277. showClear
  2278. />
  2279. )}
  2280. {inputs.type === 49 && (
  2281. <Form.Input
  2282. field='other'
  2283. label={t('智能体ID')}
  2284. placeholder={'请输入智能体ID,例如:7342866812345'}
  2285. onChange={(value) => handleInputChange('other', value)}
  2286. showClear
  2287. />
  2288. )}
  2289. {inputs.type === 1 && (
  2290. <Form.Input
  2291. field='openai_organization'
  2292. label={t('组织')}
  2293. placeholder={t('请输入组织org-xxx')}
  2294. showClear
  2295. helpText={t('组织,不填则为默认组织')}
  2296. onChange={(value) =>
  2297. handleInputChange('openai_organization', value)
  2298. }
  2299. />
  2300. )}
  2301. </Card>
  2302. </div>
  2303. {/* API Configuration Card */}
  2304. {showApiConfigCard && (
  2305. <div ref={(el) => (formSectionRefs.current.apiConfig = el)}>
  2306. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2307. {/* Header: API Config */}
  2308. <div
  2309. className='flex items-center mb-2'
  2310. onClick={handleApiConfigSecretClick}
  2311. >
  2312. <Avatar
  2313. size='small'
  2314. color='green'
  2315. className='mr-2 shadow-md'
  2316. >
  2317. <IconGlobe size={16} />
  2318. </Avatar>
  2319. <div>
  2320. <Text className='text-lg font-medium'>
  2321. {t('API 配置')}
  2322. </Text>
  2323. <div className='text-xs text-gray-600'>
  2324. {t('API 地址和相关配置')}
  2325. </div>
  2326. </div>
  2327. </div>
  2328. {inputs.type === 40 && (
  2329. <Banner
  2330. type='info'
  2331. description={
  2332. <div>
  2333. <Text strong>{t('邀请链接')}:</Text>
  2334. <Text
  2335. link
  2336. underline
  2337. className='ml-2 cursor-pointer'
  2338. onClick={() =>
  2339. window.open(
  2340. 'https://cloud.siliconflow.cn/i/hij0YNTZ',
  2341. )
  2342. }
  2343. >
  2344. https://cloud.siliconflow.cn/i/hij0YNTZ
  2345. </Text>
  2346. </div>
  2347. }
  2348. className='!rounded-lg'
  2349. />
  2350. )}
  2351. {inputs.type === 3 && (
  2352. <>
  2353. <Banner
  2354. type='warning'
  2355. description={t(
  2356. '2025年5月10日后添加的渠道,不需要再在部署的时候移除模型名称中的"."',
  2357. )}
  2358. className='!rounded-lg'
  2359. />
  2360. <div>
  2361. <Form.Input
  2362. field='base_url'
  2363. label='AZURE_OPENAI_ENDPOINT'
  2364. placeholder={t(
  2365. '请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com',
  2366. )}
  2367. onChange={(value) =>
  2368. handleInputChange('base_url', value)
  2369. }
  2370. showClear
  2371. disabled={isIonetLocked}
  2372. />
  2373. </div>
  2374. <div>
  2375. <Form.Input
  2376. field='other'
  2377. label={t('默认 API 版本')}
  2378. placeholder={t(
  2379. '请输入默认 API 版本,例如:2025-04-01-preview',
  2380. )}
  2381. onChange={(value) =>
  2382. handleInputChange('other', value)
  2383. }
  2384. showClear
  2385. />
  2386. </div>
  2387. <div>
  2388. <Form.Input
  2389. field='azure_responses_version'
  2390. label={t(
  2391. '默认 Responses API 版本,为空则使用上方版本',
  2392. )}
  2393. placeholder={t('例如:preview')}
  2394. onChange={(value) =>
  2395. handleChannelOtherSettingsChange(
  2396. 'azure_responses_version',
  2397. value,
  2398. )
  2399. }
  2400. showClear
  2401. />
  2402. </div>
  2403. </>
  2404. )}
  2405. {inputs.type === 8 && (
  2406. <>
  2407. <Banner
  2408. type='warning'
  2409. description={t(
  2410. '如果你对接的是上游One API或者New API等转发项目,请使用OpenAI类型,不要使用此类型,除非你知道你在做什么。',
  2411. )}
  2412. className='!rounded-lg'
  2413. />
  2414. <div>
  2415. <Form.Input
  2416. field='base_url'
  2417. label={t('完整的 Base URL,支持变量{model}')}
  2418. placeholder={t(
  2419. '请输入完整的URL,例如:https://api.openai.com/v1/chat/completions',
  2420. )}
  2421. onChange={(value) =>
  2422. handleInputChange('base_url', value)
  2423. }
  2424. showClear
  2425. disabled={isIonetLocked}
  2426. />
  2427. </div>
  2428. </>
  2429. )}
  2430. {inputs.type === 37 && (
  2431. <Banner
  2432. type='warning'
  2433. description={t(
  2434. 'Dify渠道只适配chatflow和agent,并且agent不支持图片!',
  2435. )}
  2436. className='!rounded-lg'
  2437. />
  2438. )}
  2439. {inputs.type !== 3 &&
  2440. inputs.type !== 8 &&
  2441. inputs.type !== 22 &&
  2442. inputs.type !== 36 &&
  2443. (inputs.type !== 45 || doubaoApiEditUnlocked) && (
  2444. <div>
  2445. <Form.Input
  2446. field='base_url'
  2447. label={t('API地址')}
  2448. placeholder={t(
  2449. '此项可选,用于通过自定义API地址来进行 API 调用,末尾不要带/v1和/',
  2450. )}
  2451. onChange={(value) =>
  2452. handleInputChange('base_url', value)
  2453. }
  2454. showClear
  2455. disabled={isIonetLocked}
  2456. extraText={t(
  2457. '对于官方渠道,new-api已经内置地址,除非是第三方代理站点或者Azure的特殊接入地址,否则不需要填写',
  2458. )}
  2459. />
  2460. </div>
  2461. )}
  2462. {inputs.type === 22 && (
  2463. <div>
  2464. <Form.Input
  2465. field='base_url'
  2466. label={t('私有部署地址')}
  2467. placeholder={t(
  2468. '请输入私有部署地址,格式为:https://fastgpt.run/api/openapi',
  2469. )}
  2470. onChange={(value) =>
  2471. handleInputChange('base_url', value)
  2472. }
  2473. showClear
  2474. disabled={isIonetLocked}
  2475. />
  2476. </div>
  2477. )}
  2478. {inputs.type === 36 && (
  2479. <div>
  2480. <Form.Input
  2481. field='base_url'
  2482. label={t(
  2483. '注意非Chat API,请务必填写正确的API地址,否则可能导致无法使用',
  2484. )}
  2485. placeholder={t(
  2486. '请输入到 /suno 前的路径,通常就是域名,例如:https://api.example.com',
  2487. )}
  2488. onChange={(value) =>
  2489. handleInputChange('base_url', value)
  2490. }
  2491. showClear
  2492. disabled={isIonetLocked}
  2493. />
  2494. </div>
  2495. )}
  2496. {inputs.type === 45 && !doubaoApiEditUnlocked && (
  2497. <div>
  2498. <Form.Select
  2499. field='base_url'
  2500. label={t('API地址')}
  2501. placeholder={t('请选择API地址')}
  2502. onChange={(value) =>
  2503. handleInputChange('base_url', value)
  2504. }
  2505. optionList={[
  2506. {
  2507. value: 'https://ark.cn-beijing.volces.com',
  2508. label: 'https://ark.cn-beijing.volces.com',
  2509. },
  2510. {
  2511. value:
  2512. 'https://ark.ap-southeast.bytepluses.com',
  2513. label:
  2514. 'https://ark.ap-southeast.bytepluses.com',
  2515. },
  2516. {
  2517. value: 'doubao-coding-plan',
  2518. label: 'Doubao Coding Plan',
  2519. },
  2520. ]}
  2521. defaultValue='https://ark.cn-beijing.volces.com'
  2522. disabled={isIonetLocked}
  2523. />
  2524. </div>
  2525. )}
  2526. </Card>
  2527. </div>
  2528. )}
  2529. {/* Model Configuration Card */}
  2530. <div ref={(el) => (formSectionRefs.current.modelConfig = el)}>
  2531. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2532. {/* Header: Model Config */}
  2533. <div className='flex items-center mb-2'>
  2534. <Avatar
  2535. size='small'
  2536. color='purple'
  2537. className='mr-2 shadow-md'
  2538. >
  2539. <IconCode size={16} />
  2540. </Avatar>
  2541. <div>
  2542. <Text className='text-lg font-medium'>
  2543. {t('模型配置')}
  2544. </Text>
  2545. <div className='text-xs text-gray-600'>
  2546. {t('模型选择和映射设置')}
  2547. </div>
  2548. </div>
  2549. </div>
  2550. <Form.Select
  2551. field='models'
  2552. label={t('模型')}
  2553. placeholder={t('请选择该渠道所支持的模型')}
  2554. rules={[{ required: true, message: t('请选择模型') }]}
  2555. multiple
  2556. filter={selectFilter}
  2557. autoClearSearchValue={false}
  2558. searchPosition='dropdown'
  2559. optionList={modelOptions}
  2560. style={{ width: '100%' }}
  2561. onChange={(value) => handleInputChange('models', value)}
  2562. renderSelectedItem={(optionNode) => {
  2563. const modelName = String(optionNode?.value ?? '');
  2564. return {
  2565. isRenderInTag: true,
  2566. content: (
  2567. <span
  2568. className='cursor-pointer select-none'
  2569. role='button'
  2570. tabIndex={0}
  2571. title={t('点击复制模型名称')}
  2572. onClick={async (e) => {
  2573. e.stopPropagation();
  2574. const ok = await copy(modelName);
  2575. if (ok) {
  2576. showSuccess(
  2577. t('已复制:{{name}}', { name: modelName }),
  2578. );
  2579. } else {
  2580. showError(t('复制失败'));
  2581. }
  2582. }}
  2583. >
  2584. {optionNode.label || modelName}
  2585. </span>
  2586. ),
  2587. };
  2588. }}
  2589. extraText={
  2590. <Space wrap>
  2591. <Button
  2592. size='small'
  2593. type='primary'
  2594. onClick={() =>
  2595. handleInputChange('models', basicModels)
  2596. }
  2597. >
  2598. {t('填入相关模型')}
  2599. </Button>
  2600. <Button
  2601. size='small'
  2602. type='secondary'
  2603. onClick={() =>
  2604. handleInputChange('models', fullModels)
  2605. }
  2606. >
  2607. {t('填入所有模型')}
  2608. </Button>
  2609. {MODEL_FETCHABLE_TYPES.has(inputs.type) && (
  2610. <Button
  2611. size='small'
  2612. type='tertiary'
  2613. onClick={() => fetchUpstreamModelList('models')}
  2614. >
  2615. {t('获取模型列表')}
  2616. </Button>
  2617. )}
  2618. {inputs.type === 4 && isEdit && (
  2619. <Button
  2620. size='small'
  2621. type='primary'
  2622. theme='light'
  2623. onClick={() => setOllamaModalVisible(true)}
  2624. >
  2625. {t('Ollama 模型管理')}
  2626. </Button>
  2627. )}
  2628. <Button
  2629. size='small'
  2630. type='warning'
  2631. onClick={() => handleInputChange('models', [])}
  2632. >
  2633. {t('清除所有模型')}
  2634. </Button>
  2635. <Button
  2636. size='small'
  2637. type='tertiary'
  2638. onClick={() => {
  2639. if (inputs.models.length === 0) {
  2640. showInfo(t('没有模型可以复制'));
  2641. return;
  2642. }
  2643. try {
  2644. copy(inputs.models.join(','));
  2645. showSuccess(t('模型列表已复制到剪贴板'));
  2646. } catch (error) {
  2647. showError(t('复制失败'));
  2648. }
  2649. }}
  2650. >
  2651. {t('复制所有模型')}
  2652. </Button>
  2653. {modelGroups &&
  2654. modelGroups.length > 0 &&
  2655. modelGroups.map((group) => (
  2656. <Button
  2657. key={group.id}
  2658. size='small'
  2659. type='primary'
  2660. onClick={() => {
  2661. let items = [];
  2662. try {
  2663. if (Array.isArray(group.items)) {
  2664. items = group.items;
  2665. } else if (
  2666. typeof group.items === 'string'
  2667. ) {
  2668. const parsed = JSON.parse(
  2669. group.items || '[]',
  2670. );
  2671. if (Array.isArray(parsed)) items = parsed;
  2672. }
  2673. } catch {}
  2674. const current =
  2675. formApiRef.current?.getValue('models') ||
  2676. inputs.models ||
  2677. [];
  2678. const merged = Array.from(
  2679. new Set(
  2680. [...current, ...items]
  2681. .map((m) => (m || '').trim())
  2682. .filter(Boolean),
  2683. ),
  2684. );
  2685. handleInputChange('models', merged);
  2686. }}
  2687. >
  2688. {group.name}
  2689. </Button>
  2690. ))}
  2691. </Space>
  2692. }
  2693. />
  2694. <Form.Input
  2695. field='custom_model'
  2696. label={t('自定义模型名称')}
  2697. placeholder={t('输入自定义模型名称')}
  2698. onChange={(value) => setCustomModel(value.trim())}
  2699. value={customModel}
  2700. suffix={
  2701. <Button
  2702. size='small'
  2703. type='primary'
  2704. onClick={addCustomModels}
  2705. >
  2706. {t('填入')}
  2707. </Button>
  2708. }
  2709. />
  2710. <Form.Input
  2711. field='test_model'
  2712. label={t('默认测试模型')}
  2713. placeholder={t('不填则为模型列表第一个')}
  2714. onChange={(value) =>
  2715. handleInputChange('test_model', value)
  2716. }
  2717. showClear
  2718. />
  2719. <JSONEditor
  2720. key={`model_mapping-${isEdit ? channelId : 'new'}`}
  2721. field='model_mapping'
  2722. label={t('模型重定向')}
  2723. placeholder={
  2724. t(
  2725. '此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:',
  2726. ) +
  2727. `\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`
  2728. }
  2729. value={inputs.model_mapping || ''}
  2730. onChange={(value) =>
  2731. handleInputChange('model_mapping', value)
  2732. }
  2733. template={MODEL_MAPPING_EXAMPLE}
  2734. templateLabel={t('填入模板')}
  2735. editorType='keyValue'
  2736. formApi={formApiRef.current}
  2737. renderStringValueSuffix={({ pairKey, value }) => {
  2738. if (!MODEL_FETCHABLE_TYPES.has(inputs.type)) {
  2739. return null;
  2740. }
  2741. const disabled = !String(pairKey ?? '').trim();
  2742. return (
  2743. <Tooltip content={t('选择模型')}>
  2744. <Button
  2745. type='tertiary'
  2746. theme='borderless'
  2747. size='small'
  2748. icon={<IconSearch size={14} />}
  2749. disabled={disabled}
  2750. onClick={(e) => {
  2751. e.stopPropagation();
  2752. openModelMappingValueModal({ pairKey, value });
  2753. }}
  2754. />
  2755. </Tooltip>
  2756. );
  2757. }}
  2758. extraText={t(
  2759. '键为请求中的模型名称,值为要替换的模型名称',
  2760. )}
  2761. />
  2762. </Card>
  2763. </div>
  2764. {/* Advanced Settings Card */}
  2765. <div
  2766. ref={(el) => (formSectionRefs.current.advancedSettings = el)}
  2767. >
  2768. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2769. {/* Header: Advanced Settings */}
  2770. <div className='flex items-center mb-2'>
  2771. <Avatar
  2772. size='small'
  2773. color='orange'
  2774. className='mr-2 shadow-md'
  2775. >
  2776. <IconSetting size={16} />
  2777. </Avatar>
  2778. <div>
  2779. <Text className='text-lg font-medium'>
  2780. {t('高级设置')}
  2781. </Text>
  2782. <div className='text-xs text-gray-600'>
  2783. {t('渠道的高级配置选项')}
  2784. </div>
  2785. </div>
  2786. </div>
  2787. <Form.Select
  2788. field='groups'
  2789. label={t('分组')}
  2790. placeholder={t('请选择可以使用该渠道的分组')}
  2791. multiple
  2792. allowAdditions
  2793. additionLabel={t(
  2794. '请在系统设置页面编辑分组倍率以添加新的分组:',
  2795. )}
  2796. optionList={groupOptions}
  2797. style={{ width: '100%' }}
  2798. onChange={(value) => handleInputChange('groups', value)}
  2799. />
  2800. <Form.Input
  2801. field='tag'
  2802. label={t('渠道标签')}
  2803. placeholder={t('渠道标签')}
  2804. showClear
  2805. onChange={(value) => handleInputChange('tag', value)}
  2806. />
  2807. <Form.TextArea
  2808. field='remark'
  2809. label={t('备注')}
  2810. placeholder={t('请输入备注(仅管理员可见)')}
  2811. maxLength={255}
  2812. showClear
  2813. onChange={(value) => handleInputChange('remark', value)}
  2814. />
  2815. <Row gutter={12}>
  2816. <Col span={12}>
  2817. <Form.InputNumber
  2818. field='priority'
  2819. label={t('渠道优先级')}
  2820. placeholder={t('渠道优先级')}
  2821. min={0}
  2822. onNumberChange={(value) =>
  2823. handleInputChange('priority', value)
  2824. }
  2825. style={{ width: '100%' }}
  2826. />
  2827. </Col>
  2828. <Col span={12}>
  2829. <Form.InputNumber
  2830. field='weight'
  2831. label={t('渠道权重')}
  2832. placeholder={t('渠道权重')}
  2833. min={0}
  2834. onNumberChange={(value) =>
  2835. handleInputChange('weight', value)
  2836. }
  2837. style={{ width: '100%' }}
  2838. />
  2839. </Col>
  2840. </Row>
  2841. <Form.Switch
  2842. field='auto_ban'
  2843. label={t('是否自动禁用')}
  2844. checkedText={t('开')}
  2845. uncheckedText={t('关')}
  2846. onChange={(value) => setAutoBan(value)}
  2847. extraText={t(
  2848. '仅当自动禁用开启时有效,关闭后不会自动禁用该渠道',
  2849. )}
  2850. initValue={autoBan}
  2851. />
  2852. <Form.TextArea
  2853. field='param_override'
  2854. label={t('参数覆盖')}
  2855. placeholder={
  2856. t(
  2857. '此项可选,用于覆盖请求参数。不支持覆盖 stream 参数',
  2858. ) +
  2859. '\n' +
  2860. t('旧格式(直接覆盖):') +
  2861. '\n{\n "temperature": 0,\n "max_tokens": 1000\n}' +
  2862. '\n\n' +
  2863. t('新格式(支持条件判断与json自定义):') +
  2864. '\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}'
  2865. }
  2866. autosize
  2867. onChange={(value) =>
  2868. handleInputChange('param_override', value)
  2869. }
  2870. extraText={
  2871. <div className='flex gap-2 flex-wrap'>
  2872. <Text
  2873. className='!text-semi-color-primary cursor-pointer'
  2874. onClick={() =>
  2875. handleInputChange(
  2876. 'param_override',
  2877. JSON.stringify({ temperature: 0 }, null, 2),
  2878. )
  2879. }
  2880. >
  2881. {t('旧格式模板')}
  2882. </Text>
  2883. <Text
  2884. className='!text-semi-color-primary cursor-pointer'
  2885. onClick={() =>
  2886. handleInputChange(
  2887. 'param_override',
  2888. JSON.stringify(
  2889. {
  2890. operations: [
  2891. {
  2892. path: 'temperature',
  2893. mode: 'set',
  2894. value: 0.7,
  2895. conditions: [
  2896. {
  2897. path: 'model',
  2898. mode: 'prefix',
  2899. value: 'gpt',
  2900. },
  2901. ],
  2902. logic: 'AND',
  2903. },
  2904. ],
  2905. },
  2906. null,
  2907. 2,
  2908. ),
  2909. )
  2910. }
  2911. >
  2912. {t('新格式模板')}
  2913. </Text>
  2914. <Text
  2915. className='!text-semi-color-primary cursor-pointer'
  2916. onClick={() => formatJsonField('param_override')}
  2917. >
  2918. {t('格式化')}
  2919. </Text>
  2920. </div>
  2921. }
  2922. showClear
  2923. />
  2924. <Form.TextArea
  2925. field='header_override'
  2926. label={t('请求头覆盖')}
  2927. placeholder={
  2928. t('此项可选,用于覆盖请求头参数') +
  2929. '\n' +
  2930. t('格式示例:') +
  2931. '\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}'
  2932. }
  2933. autosize
  2934. onChange={(value) =>
  2935. handleInputChange('header_override', value)
  2936. }
  2937. extraText={
  2938. <div className='flex flex-col gap-1'>
  2939. <div className='flex gap-2 flex-wrap items-center'>
  2940. <Text
  2941. className='!text-semi-color-primary cursor-pointer'
  2942. onClick={() =>
  2943. handleInputChange(
  2944. 'header_override',
  2945. JSON.stringify(
  2946. {
  2947. 'User-Agent':
  2948. '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',
  2949. Authorization: 'Bearer{api_key}',
  2950. },
  2951. null,
  2952. 2,
  2953. ),
  2954. )
  2955. }
  2956. >
  2957. {t('填入模板')}
  2958. </Text>
  2959. <Text
  2960. className='!text-semi-color-primary cursor-pointer'
  2961. onClick={() => formatJsonField('header_override')}
  2962. >
  2963. {t('格式化')}
  2964. </Text>
  2965. </div>
  2966. <div>
  2967. <Text type='tertiary' size='small'>
  2968. {t('支持变量:')}
  2969. </Text>
  2970. <div className='text-xs text-tertiary ml-2'>
  2971. <div>
  2972. {t('渠道密钥')}: {'{api_key}'}
  2973. </div>
  2974. </div>
  2975. </div>
  2976. </div>
  2977. }
  2978. showClear
  2979. />
  2980. <JSONEditor
  2981. key={`status_code_mapping-${isEdit ? channelId : 'new'}`}
  2982. field='status_code_mapping'
  2983. label={t('状态码复写')}
  2984. placeholder={
  2985. t(
  2986. '此项可选,用于复写返回的状态码,仅影响本地判断,不修改返回到上游的状态码,比如将claude渠道的400错误复写为500(用于重试),请勿滥用该功能,例如:',
  2987. ) +
  2988. '\n' +
  2989. JSON.stringify(STATUS_CODE_MAPPING_EXAMPLE, null, 2)
  2990. }
  2991. value={inputs.status_code_mapping || ''}
  2992. onChange={(value) =>
  2993. handleInputChange('status_code_mapping', value)
  2994. }
  2995. template={STATUS_CODE_MAPPING_EXAMPLE}
  2996. templateLabel={t('填入模板')}
  2997. editorType='keyValue'
  2998. formApi={formApiRef.current}
  2999. extraText={t(
  3000. '键为原状态码,值为要复写的状态码,仅影响本地判断',
  3001. )}
  3002. />
  3003. {/* 字段透传控制 - OpenAI 渠道 */}
  3004. {inputs.type === 1 && (
  3005. <>
  3006. <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
  3007. {t('字段透传控制')}
  3008. </div>
  3009. <Form.Switch
  3010. field='allow_service_tier'
  3011. label={t('允许 service_tier 透传')}
  3012. checkedText={t('开')}
  3013. uncheckedText={t('关')}
  3014. onChange={(value) =>
  3015. handleChannelOtherSettingsChange(
  3016. 'allow_service_tier',
  3017. value,
  3018. )
  3019. }
  3020. extraText={t(
  3021. 'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
  3022. )}
  3023. />
  3024. <Form.Switch
  3025. field='disable_store'
  3026. label={t('禁用 store 透传')}
  3027. checkedText={t('开')}
  3028. uncheckedText={t('关')}
  3029. onChange={(value) =>
  3030. handleChannelOtherSettingsChange(
  3031. 'disable_store',
  3032. value,
  3033. )
  3034. }
  3035. extraText={t(
  3036. 'store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用',
  3037. )}
  3038. />
  3039. <Form.Switch
  3040. field='allow_safety_identifier'
  3041. label={t('允许 safety_identifier 透传')}
  3042. checkedText={t('开')}
  3043. uncheckedText={t('关')}
  3044. onChange={(value) =>
  3045. handleChannelOtherSettingsChange(
  3046. 'allow_safety_identifier',
  3047. value,
  3048. )
  3049. }
  3050. extraText={t(
  3051. 'safety_identifier 字段用于帮助 OpenAI 识别可能违反使用政策的应用程序用户。默认关闭以保护用户隐私',
  3052. )}
  3053. />
  3054. </>
  3055. )}
  3056. {/* 字段透传控制 - Claude 渠道 */}
  3057. {inputs.type === 14 && (
  3058. <>
  3059. <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
  3060. {t('字段透传控制')}
  3061. </div>
  3062. <Form.Switch
  3063. field='allow_service_tier'
  3064. label={t('允许 service_tier 透传')}
  3065. checkedText={t('开')}
  3066. uncheckedText={t('关')}
  3067. onChange={(value) =>
  3068. handleChannelOtherSettingsChange(
  3069. 'allow_service_tier',
  3070. value,
  3071. )
  3072. }
  3073. extraText={t(
  3074. 'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
  3075. )}
  3076. />
  3077. </>
  3078. )}
  3079. </Card>
  3080. </div>
  3081. {/* Channel Extra Settings Card */}
  3082. <div
  3083. ref={(el) =>
  3084. (formSectionRefs.current.channelExtraSettings = el)
  3085. }
  3086. >
  3087. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  3088. {/* Header: Channel Extra Settings */}
  3089. <div className='flex items-center mb-2'>
  3090. <Avatar
  3091. size='small'
  3092. color='violet'
  3093. className='mr-2 shadow-md'
  3094. >
  3095. <IconBolt size={16} />
  3096. </Avatar>
  3097. <div>
  3098. <Text className='text-lg font-medium'>
  3099. {t('渠道额外设置')}
  3100. </Text>
  3101. </div>
  3102. </div>
  3103. {inputs.type === 1 && (
  3104. <Form.Switch
  3105. field='force_format'
  3106. label={t('强制格式化')}
  3107. checkedText={t('开')}
  3108. uncheckedText={t('关')}
  3109. onChange={(value) =>
  3110. handleChannelSettingsChange('force_format', value)
  3111. }
  3112. extraText={t(
  3113. '强制将响应格式化为 OpenAI 标准格式(只适用于OpenAI渠道类型)',
  3114. )}
  3115. />
  3116. )}
  3117. <Form.Switch
  3118. field='thinking_to_content'
  3119. label={t('思考内容转换')}
  3120. checkedText={t('开')}
  3121. uncheckedText={t('关')}
  3122. onChange={(value) =>
  3123. handleChannelSettingsChange(
  3124. 'thinking_to_content',
  3125. value,
  3126. )
  3127. }
  3128. extraText={t(
  3129. '将 reasoning_content 转换为 <think> 标签拼接到内容中',
  3130. )}
  3131. />
  3132. <Form.Switch
  3133. field='pass_through_body_enabled'
  3134. label={t('透传请求体')}
  3135. checkedText={t('开')}
  3136. uncheckedText={t('关')}
  3137. onChange={(value) =>
  3138. handleChannelSettingsChange(
  3139. 'pass_through_body_enabled',
  3140. value,
  3141. )
  3142. }
  3143. extraText={t('启用请求体透传功能')}
  3144. />
  3145. <Form.Input
  3146. field='proxy'
  3147. label={t('代理地址')}
  3148. placeholder={t('例如: socks5://user:pass@host:port')}
  3149. onChange={(value) =>
  3150. handleChannelSettingsChange('proxy', value)
  3151. }
  3152. showClear
  3153. extraText={t('用于配置网络代理,支持 socks5 协议')}
  3154. />
  3155. <Form.TextArea
  3156. field='system_prompt'
  3157. label={t('系统提示词')}
  3158. placeholder={t(
  3159. '输入系统提示词,用户的系统提示词将优先于此设置',
  3160. )}
  3161. onChange={(value) =>
  3162. handleChannelSettingsChange('system_prompt', value)
  3163. }
  3164. autosize
  3165. showClear
  3166. extraText={t(
  3167. '用户优先:如果用户在请求中指定了系统提示词,将优先使用用户的设置',
  3168. )}
  3169. />
  3170. <Form.Switch
  3171. field='system_prompt_override'
  3172. label={t('系统提示词拼接')}
  3173. checkedText={t('开')}
  3174. uncheckedText={t('关')}
  3175. onChange={(value) =>
  3176. handleChannelSettingsChange(
  3177. 'system_prompt_override',
  3178. value,
  3179. )
  3180. }
  3181. extraText={t(
  3182. '如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
  3183. )}
  3184. />
  3185. </Card>
  3186. </div>
  3187. </div>
  3188. </Spin>
  3189. )}
  3190. </Form>
  3191. <ImagePreview
  3192. src={modalImageUrl}
  3193. visible={isModalOpenurl}
  3194. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  3195. />
  3196. </SideSheet>
  3197. {/* 使用通用安全验证模态框 */}
  3198. <SecureVerificationModal
  3199. visible={isModalVisible}
  3200. verificationMethods={verificationMethods}
  3201. verificationState={verificationState}
  3202. onVerify={executeVerification}
  3203. onCancel={cancelVerification}
  3204. onCodeChange={setVerificationCode}
  3205. onMethodSwitch={switchVerificationMethod}
  3206. title={verificationState.title}
  3207. description={verificationState.description}
  3208. />
  3209. {/* 使用ChannelKeyDisplay组件显示密钥 */}
  3210. <Modal
  3211. title={
  3212. <div className='flex items-center'>
  3213. <div className='w-8 h-8 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center mr-3'>
  3214. <svg
  3215. className='w-4 h-4 text-green-600 dark:text-green-400'
  3216. fill='currentColor'
  3217. viewBox='0 0 20 20'
  3218. >
  3219. <path
  3220. fillRule='evenodd'
  3221. 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'
  3222. clipRule='evenodd'
  3223. />
  3224. </svg>
  3225. </div>
  3226. {t('渠道密钥信息')}
  3227. </div>
  3228. }
  3229. visible={keyDisplayState.showModal}
  3230. onCancel={resetKeyDisplayState}
  3231. footer={
  3232. <Button type='primary' onClick={resetKeyDisplayState}>
  3233. {t('完成')}
  3234. </Button>
  3235. }
  3236. width={700}
  3237. style={{ maxWidth: '90vw' }}
  3238. >
  3239. <ChannelKeyDisplay
  3240. keyData={keyDisplayState.keyData}
  3241. showSuccessIcon={true}
  3242. successText={t('密钥获取成功')}
  3243. showWarning={true}
  3244. warningText={t(
  3245. '请妥善保管密钥信息,不要泄露给他人。如有安全疑虑,请及时更换密钥。',
  3246. )}
  3247. />
  3248. </Modal>
  3249. <ModelSelectModal
  3250. visible={modelModalVisible}
  3251. models={fetchedModels}
  3252. selected={inputs.models}
  3253. redirectModels={redirectModelList}
  3254. onConfirm={(selectedModels) => {
  3255. handleInputChange('models', selectedModels);
  3256. showSuccess(t('模型列表已更新'));
  3257. setModelModalVisible(false);
  3258. }}
  3259. onCancel={() => setModelModalVisible(false)}
  3260. />
  3261. <SingleModelSelectModal
  3262. visible={modelMappingValueModalVisible}
  3263. models={modelMappingValueModalModels}
  3264. selected={modelMappingValueSelected}
  3265. onConfirm={(selectedModel) => {
  3266. const modelName = String(selectedModel ?? '').trim();
  3267. if (!modelName) {
  3268. showError(t('请先选择模型!'));
  3269. return;
  3270. }
  3271. const mappingKey = String(modelMappingValueKey ?? '').trim();
  3272. if (!mappingKey) {
  3273. setModelMappingValueModalVisible(false);
  3274. return;
  3275. }
  3276. let parsed = {};
  3277. const currentMapping = inputs.model_mapping;
  3278. if (typeof currentMapping === 'string' && currentMapping.trim()) {
  3279. try {
  3280. parsed = JSON.parse(currentMapping);
  3281. } catch (error) {
  3282. parsed = {};
  3283. }
  3284. } else if (
  3285. currentMapping &&
  3286. typeof currentMapping === 'object' &&
  3287. !Array.isArray(currentMapping)
  3288. ) {
  3289. parsed = currentMapping;
  3290. }
  3291. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
  3292. parsed = {};
  3293. }
  3294. parsed[mappingKey] = modelName;
  3295. const nextMapping = JSON.stringify(parsed, null, 2);
  3296. handleInputChange('model_mapping', nextMapping);
  3297. if (formApiRef.current) {
  3298. formApiRef.current.setValue('model_mapping', nextMapping);
  3299. }
  3300. setModelMappingValueModalVisible(false);
  3301. }}
  3302. onCancel={() => setModelMappingValueModalVisible(false)}
  3303. />
  3304. <OllamaModelModal
  3305. visible={ollamaModalVisible}
  3306. onCancel={() => setOllamaModalVisible(false)}
  3307. channelId={channelId}
  3308. channelInfo={inputs}
  3309. onModelsUpdate={(options = {}) => {
  3310. // 当模型更新后,重新获取模型列表以更新表单
  3311. fetchUpstreamModelList('models', { silent: !!options.silent });
  3312. }}
  3313. onApplyModels={({ mode, modelIds } = {}) => {
  3314. if (!Array.isArray(modelIds) || modelIds.length === 0) {
  3315. return;
  3316. }
  3317. const existingModels = Array.isArray(inputs.models)
  3318. ? inputs.models.map(String)
  3319. : [];
  3320. const incoming = modelIds.map(String);
  3321. const nextModels = Array.from(
  3322. new Set([...existingModels, ...incoming]),
  3323. );
  3324. handleInputChange('models', nextModels);
  3325. if (formApiRef.current) {
  3326. formApiRef.current.setValue('models', nextModels);
  3327. }
  3328. showSuccess(t('模型列表已追加更新'));
  3329. }}
  3330. />
  3331. </>
  3332. );
  3333. };
  3334. export default EditChannelModal;