You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

3706 lines
138 KiB

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