EditChannelModal.jsx 115 KB

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