EditChannelModal.jsx 140 KB

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