Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

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