EditChannelModal.jsx 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101
  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. <Form.Input
  3119. field='upstream_model_update_ignored_models'
  3120. label={t('已忽略模型')}
  3121. placeholder={t('例如:gpt-4.1-nano,gpt-4o-mini')}
  3122. onChange={(value) =>
  3123. handleInputChange(
  3124. 'upstream_model_update_ignored_models',
  3125. value,
  3126. )
  3127. }
  3128. showClear
  3129. />
  3130. </>
  3131. )}
  3132. <Form.Input
  3133. field='test_model'
  3134. label={t('默认测试模型')}
  3135. placeholder={t('不填则为模型列表第一个')}
  3136. onChange={(value) =>
  3137. handleInputChange('test_model', value)
  3138. }
  3139. showClear
  3140. />
  3141. <JSONEditor
  3142. key={`model_mapping-${isEdit ? channelId : 'new'}`}
  3143. field='model_mapping'
  3144. label={t('模型重定向')}
  3145. placeholder={
  3146. t(
  3147. '此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:',
  3148. ) +
  3149. `\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`
  3150. }
  3151. value={inputs.model_mapping || ''}
  3152. onChange={(value) =>
  3153. handleInputChange('model_mapping', value)
  3154. }
  3155. template={MODEL_MAPPING_EXAMPLE}
  3156. templateLabel={t('填入模板')}
  3157. editorType='keyValue'
  3158. formApi={formApiRef.current}
  3159. renderStringValueSuffix={({ pairKey, value }) => {
  3160. if (!MODEL_FETCHABLE_CHANNEL_TYPES.has(inputs.type)) {
  3161. return null;
  3162. }
  3163. const disabled = !String(pairKey ?? '').trim();
  3164. return (
  3165. <Tooltip content={t('选择模型')}>
  3166. <Button
  3167. type='tertiary'
  3168. theme='borderless'
  3169. size='small'
  3170. icon={<IconSearch size={14} />}
  3171. disabled={disabled}
  3172. onClick={(e) => {
  3173. e.stopPropagation();
  3174. openModelMappingValueModal({ pairKey, value });
  3175. }}
  3176. />
  3177. </Tooltip>
  3178. );
  3179. }}
  3180. extraText={t(
  3181. '键为请求中的模型名称,值为要替换的模型名称',
  3182. )}
  3183. />
  3184. </Card>
  3185. </div>
  3186. {/* Advanced Settings Card */}
  3187. <div
  3188. ref={(el) => (formSectionRefs.current.advancedSettings = el)}
  3189. >
  3190. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  3191. {/* Header: Advanced Settings */}
  3192. <div className='flex items-center mb-2'>
  3193. <Avatar
  3194. size='small'
  3195. color='orange'
  3196. className='mr-2 shadow-md'
  3197. >
  3198. <IconSetting size={16} />
  3199. </Avatar>
  3200. <div>
  3201. <Text className='text-lg font-medium'>
  3202. {t('高级设置')}
  3203. </Text>
  3204. <div className='text-xs text-gray-600'>
  3205. {t('渠道的高级配置选项')}
  3206. </div>
  3207. </div>
  3208. </div>
  3209. <Form.Select
  3210. field='groups'
  3211. label={t('分组')}
  3212. placeholder={t('请选择可以使用该渠道的分组')}
  3213. multiple
  3214. allowAdditions
  3215. additionLabel={t(
  3216. '请在系统设置页面编辑分组倍率以添加新的分组:',
  3217. )}
  3218. optionList={groupOptions}
  3219. style={{ width: '100%' }}
  3220. onChange={(value) => handleInputChange('groups', value)}
  3221. />
  3222. <Form.Input
  3223. field='tag'
  3224. label={t('渠道标签')}
  3225. placeholder={t('渠道标签')}
  3226. showClear
  3227. onChange={(value) => handleInputChange('tag', value)}
  3228. />
  3229. <Form.TextArea
  3230. field='remark'
  3231. label={t('备注')}
  3232. placeholder={t('请输入备注(仅管理员可见)')}
  3233. maxLength={255}
  3234. showClear
  3235. onChange={(value) => handleInputChange('remark', value)}
  3236. />
  3237. <Row gutter={12}>
  3238. <Col span={12}>
  3239. <Form.InputNumber
  3240. field='priority'
  3241. label={t('渠道优先级')}
  3242. placeholder={t('渠道优先级')}
  3243. min={0}
  3244. onNumberChange={(value) =>
  3245. handleInputChange('priority', value)
  3246. }
  3247. style={{ width: '100%' }}
  3248. />
  3249. </Col>
  3250. <Col span={12}>
  3251. <Form.InputNumber
  3252. field='weight'
  3253. label={t('渠道权重')}
  3254. placeholder={t('渠道权重')}
  3255. min={0}
  3256. onNumberChange={(value) =>
  3257. handleInputChange('weight', value)
  3258. }
  3259. style={{ width: '100%' }}
  3260. />
  3261. </Col>
  3262. </Row>
  3263. <Form.Switch
  3264. field='auto_ban'
  3265. label={t('是否自动禁用')}
  3266. checkedText={t('开')}
  3267. uncheckedText={t('关')}
  3268. onChange={(value) => setAutoBan(value)}
  3269. extraText={t(
  3270. '仅当自动禁用开启时有效,关闭后不会自动禁用该渠道',
  3271. )}
  3272. initValue={autoBan}
  3273. />
  3274. <Form.Switch
  3275. field='upstream_model_update_auto_sync_enabled'
  3276. label={t('是否自动同步上游模型更新')}
  3277. checkedText={t('开')}
  3278. uncheckedText={t('关')}
  3279. disabled={!inputs.upstream_model_update_check_enabled}
  3280. onChange={(value) =>
  3281. handleChannelOtherSettingsChange(
  3282. 'upstream_model_update_auto_sync_enabled',
  3283. value,
  3284. )
  3285. }
  3286. extraText={t(
  3287. '开启后检测到新增模型会自动加入当前渠道模型列表',
  3288. )}
  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;