EditChannelModal.jsx 153 KB

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