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.
 
 
 

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