SettingGlobalModel.jsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 } from 'react';
  16. import {
  17. Button,
  18. Col,
  19. Form,
  20. Row,
  21. Spin,
  22. Banner,
  23. Tag,
  24. Divider,
  25. } from '@douyinfe/semi-ui';
  26. import {
  27. compareObjects,
  28. API,
  29. showError,
  30. showSuccess,
  31. showWarning,
  32. verifyJSON,
  33. } from '../../../helpers';
  34. import { useTranslation } from 'react-i18next';
  35. const thinkingExample = JSON.stringify(
  36. ['moonshotai/kimi-k2-thinking', 'kimi-k2-thinking'],
  37. null,
  38. 2,
  39. );
  40. const chatCompletionsToResponsesPolicyExample = JSON.stringify(
  41. {
  42. enabled: true,
  43. all_channels: false,
  44. channel_ids: [1, 2],
  45. channel_types: [1],
  46. model_patterns: ['^gpt-4o.*$', '^gpt-5.*$'],
  47. },
  48. null,
  49. 2,
  50. );
  51. const chatCompletionsToResponsesPolicyAllChannelsExample = JSON.stringify(
  52. {
  53. enabled: true,
  54. all_channels: true,
  55. model_patterns: ['^gpt-4o.*$', '^gpt-5.*$'],
  56. },
  57. null,
  58. 2,
  59. );
  60. const defaultGlobalSettingInputs = {
  61. 'global.pass_through_request_enabled': false,
  62. 'global.thinking_model_blacklist': '[]',
  63. 'global.chat_completions_to_responses_policy': '{}',
  64. 'general_setting.ping_interval_enabled': false,
  65. 'general_setting.ping_interval_seconds': 60,
  66. };
  67. export default function SettingGlobalModel(props) {
  68. const { t } = useTranslation();
  69. const [loading, setLoading] = useState(false);
  70. const [inputs, setInputs] = useState(defaultGlobalSettingInputs);
  71. const refForm = useRef();
  72. const [inputsRow, setInputsRow] = useState(defaultGlobalSettingInputs);
  73. const chatCompletionsToResponsesPolicyKey =
  74. 'global.chat_completions_to_responses_policy';
  75. const setChatCompletionsToResponsesPolicyValue = (value) => {
  76. setInputs((prev) => ({
  77. ...prev,
  78. [chatCompletionsToResponsesPolicyKey]: value,
  79. }));
  80. if (refForm.current) {
  81. refForm.current.setValue(chatCompletionsToResponsesPolicyKey, value);
  82. }
  83. };
  84. const normalizeValueBeforeSave = (key, value) => {
  85. if (key === 'global.thinking_model_blacklist') {
  86. const text = typeof value === 'string' ? value.trim() : '';
  87. return text === '' ? '[]' : value;
  88. }
  89. if (key === 'global.chat_completions_to_responses_policy') {
  90. const text = typeof value === 'string' ? value.trim() : '';
  91. return text === '' ? '{}' : value;
  92. }
  93. return value;
  94. };
  95. function onSubmit() {
  96. const updateArray = compareObjects(inputs, inputsRow);
  97. if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
  98. const requestQueue = updateArray.map((item) => {
  99. const normalizedValue = normalizeValueBeforeSave(
  100. item.key,
  101. inputs[item.key],
  102. );
  103. let value = String(normalizedValue);
  104. return API.put('/api/option/', {
  105. key: item.key,
  106. value,
  107. });
  108. });
  109. setLoading(true);
  110. Promise.all(requestQueue)
  111. .then((res) => {
  112. if (requestQueue.length === 1) {
  113. if (res.includes(undefined)) return;
  114. } else if (requestQueue.length > 1) {
  115. if (res.includes(undefined))
  116. return showError(t('部分保存失败,请重试'));
  117. }
  118. showSuccess(t('保存成功'));
  119. props.refresh();
  120. })
  121. .catch(() => {
  122. showError(t('保存失败,请重试'));
  123. })
  124. .finally(() => {
  125. setLoading(false);
  126. });
  127. }
  128. useEffect(() => {
  129. const currentInputs = {};
  130. for (const key of Object.keys(defaultGlobalSettingInputs)) {
  131. if (props.options[key] !== undefined) {
  132. let value = props.options[key];
  133. if (key === 'global.thinking_model_blacklist') {
  134. try {
  135. value =
  136. value && String(value).trim() !== ''
  137. ? JSON.stringify(JSON.parse(value), null, 2)
  138. : defaultGlobalSettingInputs[key];
  139. } catch (error) {
  140. value = defaultGlobalSettingInputs[key];
  141. }
  142. }
  143. if (key === 'global.chat_completions_to_responses_policy') {
  144. try {
  145. value =
  146. value && String(value).trim() !== ''
  147. ? JSON.stringify(JSON.parse(value), null, 2)
  148. : defaultGlobalSettingInputs[key];
  149. } catch (error) {
  150. value = defaultGlobalSettingInputs[key];
  151. }
  152. }
  153. currentInputs[key] = value;
  154. } else {
  155. currentInputs[key] = defaultGlobalSettingInputs[key];
  156. }
  157. }
  158. setInputs(currentInputs);
  159. setInputsRow(structuredClone(currentInputs));
  160. if (refForm.current) {
  161. refForm.current.setValues(currentInputs);
  162. }
  163. }, [props.options]);
  164. return (
  165. <>
  166. <Spin spinning={loading}>
  167. <Form
  168. values={inputs}
  169. getFormApi={(formAPI) => (refForm.current = formAPI)}
  170. style={{ marginBottom: 15 }}
  171. >
  172. <Form.Section text={t('全局设置')}>
  173. <Row>
  174. <Col xs={24} sm={12} md={8} lg={8} xl={8}>
  175. <Form.Switch
  176. label={t('启用请求透传')}
  177. field={'global.pass_through_request_enabled'}
  178. onChange={(value) =>
  179. setInputs({
  180. ...inputs,
  181. 'global.pass_through_request_enabled': value,
  182. })
  183. }
  184. extraText={t(
  185. '开启后,所有请求将直接透传给上游,不会进行任何处理(重定向和渠道适配也将失效),请谨慎开启',
  186. )}
  187. />
  188. </Col>
  189. </Row>
  190. <Row>
  191. <Col span={24}>
  192. <Form.TextArea
  193. label={t('禁用思考处理的模型列表')}
  194. field={'global.thinking_model_blacklist'}
  195. placeholder={t('例如:') + '\n' + thinkingExample}
  196. rows={4}
  197. rules={[
  198. {
  199. validator: (rule, value) => {
  200. if (!value || value.trim() === '') return true;
  201. return verifyJSON(value);
  202. },
  203. message: t('不是合法的 JSON 字符串'),
  204. },
  205. ]}
  206. extraText={t(
  207. '列出的模型将不会自动添加或移除-thinking/-nothinking 后缀',
  208. )}
  209. onChange={(value) =>
  210. setInputs({
  211. ...inputs,
  212. 'global.thinking_model_blacklist': value,
  213. })
  214. }
  215. />
  216. </Col>
  217. </Row>
  218. <Form.Section
  219. text={
  220. <span
  221. style={{
  222. fontSize: 14,
  223. fontWeight: 600,
  224. display: 'inline-flex',
  225. alignItems: 'center',
  226. gap: 8,
  227. flexWrap: 'wrap',
  228. }}
  229. >
  230. {t('ChatCompletions→Responses 兼容配置')}
  231. <Tag color='orange' size='small'>
  232. 测试版
  233. </Tag>
  234. </span>
  235. }
  236. >
  237. <Row style={{ marginTop: 10 }}>
  238. <Col span={24}>
  239. <Banner
  240. type='warning'
  241. description={t(
  242. '提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。',
  243. )}
  244. />
  245. </Col>
  246. </Row>
  247. <Row style={{ marginTop: 10 }}>
  248. <Col span={24}>
  249. <Form.TextArea
  250. label={t('参数配置')}
  251. field={chatCompletionsToResponsesPolicyKey}
  252. placeholder={
  253. t('例如(指定渠道):') +
  254. '\n' +
  255. chatCompletionsToResponsesPolicyExample +
  256. '\n\n' +
  257. t('例如(全渠道):') +
  258. '\n' +
  259. chatCompletionsToResponsesPolicyAllChannelsExample
  260. }
  261. rows={8}
  262. rules={[
  263. {
  264. validator: (rule, value) => {
  265. if (!value || value.trim() === '') return true;
  266. return verifyJSON(value);
  267. },
  268. message: t('不是合法的 JSON 字符串'),
  269. },
  270. ]}
  271. onChange={(value) =>
  272. setInputs((prev) => ({
  273. ...prev,
  274. [chatCompletionsToResponsesPolicyKey]: value,
  275. }))
  276. }
  277. />
  278. </Col>
  279. </Row>
  280. <Row style={{ marginTop: 10, marginBottom: 16 }}>
  281. <Col span={24}>
  282. <div
  283. style={{
  284. display: 'flex',
  285. gap: 8,
  286. flexWrap: 'wrap',
  287. alignItems: 'center',
  288. }}
  289. >
  290. <Button
  291. type='secondary'
  292. size='small'
  293. onClick={() =>
  294. setChatCompletionsToResponsesPolicyValue(
  295. chatCompletionsToResponsesPolicyExample,
  296. )
  297. }
  298. >
  299. {t('填充模板(指定渠道)')}
  300. </Button>
  301. <Button
  302. type='secondary'
  303. size='small'
  304. onClick={() =>
  305. setChatCompletionsToResponsesPolicyValue(
  306. chatCompletionsToResponsesPolicyAllChannelsExample,
  307. )
  308. }
  309. >
  310. {t('填充模板(全渠道)')}
  311. </Button>
  312. <Button
  313. type='secondary'
  314. size='small'
  315. onClick={() => {
  316. const raw = inputs[chatCompletionsToResponsesPolicyKey];
  317. if (!raw || String(raw).trim() === '') return;
  318. try {
  319. const formatted = JSON.stringify(
  320. JSON.parse(raw),
  321. null,
  322. 2,
  323. );
  324. setChatCompletionsToResponsesPolicyValue(formatted);
  325. } catch (error) {
  326. showError(t('不是合法的 JSON 字符串'));
  327. }
  328. }}
  329. >
  330. {t('格式化 JSON')}
  331. </Button>
  332. </div>
  333. </Col>
  334. </Row>
  335. </Form.Section>
  336. <Form.Section
  337. text={
  338. <span style={{ fontSize: 14, fontWeight: 600 }}>
  339. {t('连接保活设置')}
  340. </span>
  341. }
  342. >
  343. <Row style={{ marginTop: 10 }}>
  344. <Col span={24}>
  345. <Banner
  346. type='warning'
  347. description={t(
  348. '警告:启用保活后,如果已经写入保活数据后渠道出错,系统无法重试,如果必须开启,推荐设置尽可能大的Ping间隔',
  349. )}
  350. />
  351. </Col>
  352. </Row>
  353. <Row>
  354. <Col xs={24} sm={12} md={8} lg={8} xl={8}>
  355. <Form.Switch
  356. label={t('启用Ping间隔')}
  357. field={'general_setting.ping_interval_enabled'}
  358. onChange={(value) =>
  359. setInputs({
  360. ...inputs,
  361. 'general_setting.ping_interval_enabled': value,
  362. })
  363. }
  364. extraText={t('开启后,将定期发送ping数据保持连接活跃')}
  365. />
  366. </Col>
  367. <Col xs={24} sm={12} md={8} lg={8} xl={8}>
  368. <Form.InputNumber
  369. label={t('Ping间隔(秒)')}
  370. field={'general_setting.ping_interval_seconds'}
  371. onChange={(value) =>
  372. setInputs({
  373. ...inputs,
  374. 'general_setting.ping_interval_seconds': value,
  375. })
  376. }
  377. min={1}
  378. disabled={!inputs['general_setting.ping_interval_enabled']}
  379. />
  380. </Col>
  381. </Row>
  382. </Form.Section>
  383. <Row>
  384. <Button size='default' onClick={onSubmit}>
  385. {t('保存')}
  386. </Button>
  387. </Row>
  388. </Form.Section>
  389. </Form>
  390. </Spin>
  391. </>
  392. );
  393. }