EditChannelModal.jsx 134 KB

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