EditChannelModal.jsx 132 KB

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