EditChannelModal.jsx 123 KB

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