EditChannelModal.jsx 135 KB

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