utils.jsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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 { Toast, Pagination } from '@douyinfe/semi-ui';
  16. import { toastConstants } from '../constants';
  17. import React from 'react';
  18. import { toast } from 'react-toastify';
  19. import {
  20. THINK_TAG_REGEX,
  21. MESSAGE_ROLES,
  22. } from '../constants/playground.constants';
  23. import { TABLE_COMPACT_MODES_KEY } from '../constants';
  24. import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
  25. const HTMLToastContent = ({ htmlContent }) => {
  26. return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
  27. };
  28. export default HTMLToastContent;
  29. export function isAdmin() {
  30. let user = localStorage.getItem('user');
  31. if (!user) return false;
  32. user = JSON.parse(user);
  33. return user.role >= 10;
  34. }
  35. export function isRoot() {
  36. let user = localStorage.getItem('user');
  37. if (!user) return false;
  38. user = JSON.parse(user);
  39. return user.role >= 100;
  40. }
  41. export function getSystemName() {
  42. let system_name = localStorage.getItem('system_name');
  43. if (!system_name) return 'New API';
  44. return system_name;
  45. }
  46. export function getLogo() {
  47. let logo = localStorage.getItem('logo');
  48. if (!logo) return '/logo.png';
  49. return logo;
  50. }
  51. export function getUserIdFromLocalStorage() {
  52. let user = localStorage.getItem('user');
  53. if (!user) return -1;
  54. user = JSON.parse(user);
  55. return user.id;
  56. }
  57. export function getFooterHTML() {
  58. return localStorage.getItem('footer_html');
  59. }
  60. export async function copy(text) {
  61. let okay = true;
  62. try {
  63. await navigator.clipboard.writeText(text);
  64. } catch (e) {
  65. try {
  66. // 构建 textarea 执行复制命令,保留多行文本格式
  67. const textarea = window.document.createElement('textarea');
  68. textarea.value = text;
  69. textarea.setAttribute('readonly', '');
  70. textarea.style.position = 'fixed';
  71. textarea.style.left = '-9999px';
  72. textarea.style.top = '-9999px';
  73. window.document.body.appendChild(textarea);
  74. textarea.select();
  75. window.document.execCommand('copy');
  76. window.document.body.removeChild(textarea);
  77. } catch (e) {
  78. okay = false;
  79. console.error(e);
  80. }
  81. }
  82. return okay;
  83. }
  84. // isMobile 函数已移除,请改用 useIsMobile Hook
  85. let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT };
  86. let showWarningOptions = { autoClose: toastConstants.WARNING_TIMEOUT };
  87. let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT };
  88. let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT };
  89. let showNoticeOptions = { autoClose: false };
  90. const isMobileScreen = window.matchMedia(
  91. `(max-width: ${MOBILE_BREAKPOINT - 1}px)`,
  92. ).matches;
  93. if (isMobileScreen) {
  94. showErrorOptions.position = 'top-center';
  95. // showErrorOptions.transition = 'flip';
  96. showSuccessOptions.position = 'top-center';
  97. // showSuccessOptions.transition = 'flip';
  98. showInfoOptions.position = 'top-center';
  99. // showInfoOptions.transition = 'flip';
  100. showNoticeOptions.position = 'top-center';
  101. // showNoticeOptions.transition = 'flip';
  102. }
  103. export function showError(error) {
  104. console.error(error);
  105. if (error.message) {
  106. if (error.name === 'AxiosError') {
  107. switch (error.response.status) {
  108. case 401:
  109. // 清除用户状态
  110. localStorage.removeItem('user');
  111. // toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions);
  112. window.location.href = '/login?expired=true';
  113. break;
  114. case 429:
  115. Toast.error('错误:请求次数过多,请稍后再试!');
  116. break;
  117. case 500:
  118. Toast.error('错误:服务器内部错误,请联系管理员!');
  119. break;
  120. case 405:
  121. Toast.info('本站仅作演示之用,无服务端!');
  122. break;
  123. default:
  124. Toast.error('错误:' + error.message);
  125. }
  126. return;
  127. }
  128. Toast.error('错误:' + error.message);
  129. } else {
  130. Toast.error('错误:' + error);
  131. }
  132. }
  133. export function showWarning(message) {
  134. Toast.warning(message);
  135. }
  136. export function showSuccess(message) {
  137. Toast.success(message);
  138. }
  139. export function showInfo(message) {
  140. Toast.info(message);
  141. }
  142. export function showNotice(message, isHTML = false) {
  143. if (isHTML) {
  144. toast(<HTMLToastContent htmlContent={message} />, showNoticeOptions);
  145. } else {
  146. Toast.info(message);
  147. }
  148. }
  149. export function openPage(url) {
  150. window.open(url);
  151. }
  152. export function removeTrailingSlash(url) {
  153. if (!url) return '';
  154. if (url.endsWith('/')) {
  155. return url.slice(0, -1);
  156. } else {
  157. return url;
  158. }
  159. }
  160. export function getTodayStartTimestamp() {
  161. var now = new Date();
  162. now.setHours(0, 0, 0, 0);
  163. return Math.floor(now.getTime() / 1000);
  164. }
  165. export function timestamp2string(timestamp) {
  166. let date = new Date(timestamp * 1000);
  167. let year = date.getFullYear().toString();
  168. let month = (date.getMonth() + 1).toString();
  169. let day = date.getDate().toString();
  170. let hour = date.getHours().toString();
  171. let minute = date.getMinutes().toString();
  172. let second = date.getSeconds().toString();
  173. if (month.length === 1) {
  174. month = '0' + month;
  175. }
  176. if (day.length === 1) {
  177. day = '0' + day;
  178. }
  179. if (hour.length === 1) {
  180. hour = '0' + hour;
  181. }
  182. if (minute.length === 1) {
  183. minute = '0' + minute;
  184. }
  185. if (second.length === 1) {
  186. second = '0' + second;
  187. }
  188. return (
  189. year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  190. );
  191. }
  192. export function timestamp2string1(
  193. timestamp,
  194. dataExportDefaultTime = 'hour',
  195. showYear = false,
  196. ) {
  197. let date = new Date(timestamp * 1000);
  198. let year = date.getFullYear();
  199. let month = (date.getMonth() + 1).toString();
  200. let day = date.getDate().toString();
  201. let hour = date.getHours().toString();
  202. if (month.length === 1) {
  203. month = '0' + month;
  204. }
  205. if (day.length === 1) {
  206. day = '0' + day;
  207. }
  208. if (hour.length === 1) {
  209. hour = '0' + hour;
  210. }
  211. // 仅在跨年时显示年份
  212. let str = showYear ? year + '-' + month + '-' + day : month + '-' + day;
  213. if (dataExportDefaultTime === 'hour') {
  214. str += ' ' + hour + ':00';
  215. } else if (dataExportDefaultTime === 'week') {
  216. let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000);
  217. let nextWeekYear = nextWeek.getFullYear();
  218. let nextMonth = (nextWeek.getMonth() + 1).toString();
  219. let nextDay = nextWeek.getDate().toString();
  220. if (nextMonth.length === 1) {
  221. nextMonth = '0' + nextMonth;
  222. }
  223. if (nextDay.length === 1) {
  224. nextDay = '0' + nextDay;
  225. }
  226. // 周视图结束日期也仅在跨年时显示年份
  227. let nextStr = showYear
  228. ? nextWeekYear + '-' + nextMonth + '-' + nextDay
  229. : nextMonth + '-' + nextDay;
  230. str += ' - ' + nextStr;
  231. }
  232. return str;
  233. }
  234. // 检查时间戳数组是否跨年
  235. export function isDataCrossYear(timestamps) {
  236. if (!timestamps || timestamps.length === 0) return false;
  237. const years = new Set(
  238. timestamps.map((ts) => new Date(ts * 1000).getFullYear()),
  239. );
  240. return years.size > 1;
  241. }
  242. export function downloadTextAsFile(text, filename) {
  243. let blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  244. let url = URL.createObjectURL(blob);
  245. let a = document.createElement('a');
  246. a.href = url;
  247. a.download = filename;
  248. a.click();
  249. }
  250. export const verifyJSON = (str) => {
  251. try {
  252. JSON.parse(str);
  253. } catch (e) {
  254. return false;
  255. }
  256. return true;
  257. };
  258. export function verifyJSONPromise(value) {
  259. try {
  260. JSON.parse(value);
  261. return Promise.resolve();
  262. } catch (e) {
  263. return Promise.reject('不是合法的 JSON 字符串');
  264. }
  265. }
  266. export function shouldShowPrompt(id) {
  267. let prompt = localStorage.getItem(`prompt-${id}`);
  268. return !prompt;
  269. }
  270. export function setPromptShown(id) {
  271. localStorage.setItem(`prompt-${id}`, 'true');
  272. }
  273. /**
  274. * 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组
  275. * @param {Object} oldObject - 旧对象
  276. * @param {Object} newObject - 新对象
  277. * @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue
  278. */
  279. export function compareObjects(oldObject, newObject) {
  280. const changedProperties = [];
  281. // 比较两个对象的属性
  282. for (const key in oldObject) {
  283. if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) {
  284. if (oldObject[key] !== newObject[key]) {
  285. changedProperties.push({
  286. key: key,
  287. oldValue: oldObject[key],
  288. newValue: newObject[key],
  289. });
  290. }
  291. }
  292. }
  293. return changedProperties;
  294. }
  295. // playground message
  296. // 生成唯一ID
  297. let messageId = 4;
  298. export const generateMessageId = () => `${messageId++}`;
  299. // 提取消息中的文本内容
  300. export const getTextContent = (message) => {
  301. if (!message || !message.content) return '';
  302. if (Array.isArray(message.content)) {
  303. const textContent = message.content.find((item) => item.type === 'text');
  304. return textContent?.text || '';
  305. }
  306. return typeof message.content === 'string' ? message.content : '';
  307. };
  308. // 处理 think 标签
  309. export const processThinkTags = (content, reasoningContent = '') => {
  310. if (!content || !content.includes('<think>')) {
  311. return { content, reasoningContent };
  312. }
  313. const thoughts = [];
  314. const replyParts = [];
  315. let lastIndex = 0;
  316. let match;
  317. THINK_TAG_REGEX.lastIndex = 0;
  318. while ((match = THINK_TAG_REGEX.exec(content)) !== null) {
  319. replyParts.push(content.substring(lastIndex, match.index));
  320. thoughts.push(match[1]);
  321. lastIndex = match.index + match[0].length;
  322. }
  323. replyParts.push(content.substring(lastIndex));
  324. const processedContent = replyParts
  325. .join('')
  326. .replace(/<\/?think>/g, '')
  327. .trim();
  328. const thoughtsStr = thoughts.join('\n\n---\n\n');
  329. const processedReasoningContent =
  330. reasoningContent && thoughtsStr
  331. ? `${reasoningContent}\n\n---\n\n${thoughtsStr}`
  332. : reasoningContent || thoughtsStr;
  333. return {
  334. content: processedContent,
  335. reasoningContent: processedReasoningContent,
  336. };
  337. };
  338. // 处理未完成的 think 标签
  339. export const processIncompleteThinkTags = (content, reasoningContent = '') => {
  340. if (!content) return { content: '', reasoningContent };
  341. const lastOpenThinkIndex = content.lastIndexOf('<think>');
  342. if (lastOpenThinkIndex === -1) {
  343. return processThinkTags(content, reasoningContent);
  344. }
  345. const fragmentAfterLastOpen = content.substring(lastOpenThinkIndex);
  346. if (!fragmentAfterLastOpen.includes('</think>')) {
  347. const unclosedThought = fragmentAfterLastOpen
  348. .substring('<think>'.length)
  349. .trim();
  350. const cleanContent = content.substring(0, lastOpenThinkIndex);
  351. const processedReasoningContent = unclosedThought
  352. ? reasoningContent
  353. ? `${reasoningContent}\n\n---\n\n${unclosedThought}`
  354. : unclosedThought
  355. : reasoningContent;
  356. return processThinkTags(cleanContent, processedReasoningContent);
  357. }
  358. return processThinkTags(content, reasoningContent);
  359. };
  360. // 构建消息内容(包含图片)
  361. export const buildMessageContent = (
  362. textContent,
  363. imageUrls = [],
  364. imageEnabled = false,
  365. ) => {
  366. if (!textContent && (!imageUrls || imageUrls.length === 0)) {
  367. return '';
  368. }
  369. const validImageUrls = imageUrls.filter((url) => url && url.trim() !== '');
  370. if (imageEnabled && validImageUrls.length > 0) {
  371. return [
  372. { type: 'text', text: textContent || '' },
  373. ...validImageUrls.map((url) => ({
  374. type: 'image_url',
  375. image_url: { url: url.trim() },
  376. })),
  377. ];
  378. }
  379. return textContent || '';
  380. };
  381. // 创建新消息
  382. export const createMessage = (role, content, options = {}) => ({
  383. role,
  384. content,
  385. createAt: Date.now(),
  386. id: generateMessageId(),
  387. ...options,
  388. });
  389. // 创建加载中的助手消息
  390. export const createLoadingAssistantMessage = () =>
  391. createMessage(MESSAGE_ROLES.ASSISTANT, '', {
  392. reasoningContent: '',
  393. isReasoningExpanded: true,
  394. isThinkingComplete: false,
  395. hasAutoCollapsed: false,
  396. status: 'loading',
  397. });
  398. // 检查消息是否包含图片
  399. export const hasImageContent = (message) => {
  400. return (
  401. message &&
  402. Array.isArray(message.content) &&
  403. message.content.some((item) => item.type === 'image_url')
  404. );
  405. };
  406. // 格式化消息用于API请求
  407. export const formatMessageForAPI = (message) => {
  408. if (!message) return null;
  409. return {
  410. role: message.role,
  411. content: message.content,
  412. };
  413. };
  414. // 验证消息是否有效
  415. export const isValidMessage = (message) => {
  416. return message && message.role && (message.content || message.content === '');
  417. };
  418. // 获取最后一条用户消息
  419. export const getLastUserMessage = (messages) => {
  420. if (!Array.isArray(messages)) return null;
  421. for (let i = messages.length - 1; i >= 0; i--) {
  422. if (messages[i].role === MESSAGE_ROLES.USER) {
  423. return messages[i];
  424. }
  425. }
  426. return null;
  427. };
  428. // 获取最后一条助手消息
  429. export const getLastAssistantMessage = (messages) => {
  430. if (!Array.isArray(messages)) return null;
  431. for (let i = messages.length - 1; i >= 0; i--) {
  432. if (messages[i].role === MESSAGE_ROLES.ASSISTANT) {
  433. return messages[i];
  434. }
  435. }
  436. return null;
  437. };
  438. // 计算相对时间(几天前、几小时前等)
  439. export const getRelativeTime = (publishDate) => {
  440. if (!publishDate) return '';
  441. const now = new Date();
  442. const pubDate = new Date(publishDate);
  443. // 如果日期无效,返回原始字符串
  444. if (isNaN(pubDate.getTime())) return publishDate;
  445. const diffMs = now.getTime() - pubDate.getTime();
  446. const diffSeconds = Math.floor(diffMs / 1000);
  447. const diffMinutes = Math.floor(diffSeconds / 60);
  448. const diffHours = Math.floor(diffMinutes / 60);
  449. const diffDays = Math.floor(diffHours / 24);
  450. const diffWeeks = Math.floor(diffDays / 7);
  451. const diffMonths = Math.floor(diffDays / 30);
  452. const diffYears = Math.floor(diffDays / 365);
  453. // 如果是未来时间,显示具体日期
  454. if (diffMs < 0) {
  455. return formatDateString(pubDate);
  456. }
  457. // 根据时间差返回相应的描述
  458. if (diffSeconds < 60) {
  459. return '刚刚';
  460. } else if (diffMinutes < 60) {
  461. return `${diffMinutes} 分钟前`;
  462. } else if (diffHours < 24) {
  463. return `${diffHours} 小时前`;
  464. } else if (diffDays < 7) {
  465. return `${diffDays} 天前`;
  466. } else if (diffWeeks < 4) {
  467. return `${diffWeeks} 周前`;
  468. } else if (diffMonths < 12) {
  469. return `${diffMonths} 个月前`;
  470. } else if (diffYears < 2) {
  471. return '1 年前';
  472. } else {
  473. // 超过2年显示具体日期
  474. return formatDateString(pubDate);
  475. }
  476. };
  477. // 格式化日期字符串
  478. export const formatDateString = (date) => {
  479. const year = date.getFullYear();
  480. const month = String(date.getMonth() + 1).padStart(2, '0');
  481. const day = String(date.getDate()).padStart(2, '0');
  482. return `${year}-${month}-${day}`;
  483. };
  484. // 格式化日期时间字符串(包含时间)
  485. export const formatDateTimeString = (date) => {
  486. const year = date.getFullYear();
  487. const month = String(date.getMonth() + 1).padStart(2, '0');
  488. const day = String(date.getDate()).padStart(2, '0');
  489. const hours = String(date.getHours()).padStart(2, '0');
  490. const minutes = String(date.getMinutes()).padStart(2, '0');
  491. return `${year}-${month}-${day} ${hours}:${minutes}`;
  492. };
  493. function readTableCompactModes() {
  494. try {
  495. const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY);
  496. return json ? JSON.parse(json) : {};
  497. } catch {
  498. return {};
  499. }
  500. }
  501. function writeTableCompactModes(modes) {
  502. try {
  503. localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
  504. } catch {
  505. // ignore
  506. }
  507. }
  508. export function getTableCompactMode(tableKey = 'global') {
  509. const modes = readTableCompactModes();
  510. return !!modes[tableKey];
  511. }
  512. export function setTableCompactMode(compact, tableKey = 'global') {
  513. const modes = readTableCompactModes();
  514. modes[tableKey] = compact;
  515. writeTableCompactModes(modes);
  516. }
  517. // -------------------------------
  518. // Select 组件统一过滤逻辑
  519. // 使用方式: <Select filter={selectFilter} ... />
  520. // 统一的 Select 搜索过滤逻辑 -- 支持同时匹配 option.value 与 option.label
  521. export const selectFilter = (input, option) => {
  522. if (!input) return true;
  523. const keyword = input.trim().toLowerCase();
  524. const valueText = (option?.value ?? '').toString().toLowerCase();
  525. const labelText = (option?.label ?? '').toString().toLowerCase();
  526. return valueText.includes(keyword) || labelText.includes(keyword);
  527. };
  528. // -------------------------------
  529. // 模型定价计算工具函数
  530. export const calculateModelPrice = ({
  531. record,
  532. selectedGroup,
  533. groupRatio,
  534. tokenUnit,
  535. displayPrice,
  536. currency,
  537. quotaDisplayType = 'USD',
  538. precision = 4,
  539. }) => {
  540. // 1. 选择实际使用的分组
  541. let usedGroup = selectedGroup;
  542. let usedGroupRatio = groupRatio[selectedGroup];
  543. if (selectedGroup === 'all' || usedGroupRatio === undefined) {
  544. // 在模型可用分组中选择倍率最小的分组,若无则使用 1
  545. let minRatio = Number.POSITIVE_INFINITY;
  546. if (
  547. Array.isArray(record.enable_groups) &&
  548. record.enable_groups.length > 0
  549. ) {
  550. record.enable_groups.forEach((g) => {
  551. const r = groupRatio[g];
  552. if (r !== undefined && r < minRatio) {
  553. minRatio = r;
  554. usedGroup = g;
  555. usedGroupRatio = r;
  556. }
  557. });
  558. }
  559. // 如果找不到合适分组倍率,回退为 1
  560. if (usedGroupRatio === undefined) {
  561. usedGroupRatio = 1;
  562. }
  563. }
  564. // 2. 动态计费(tiered_expr)
  565. if (record.billing_mode === 'tiered_expr' && record.billing_expr) {
  566. return {
  567. isDynamicPricing: true,
  568. billingExpr: record.billing_expr,
  569. usedGroup,
  570. usedGroupRatio,
  571. };
  572. }
  573. // 3. 根据计费类型计算价格
  574. if (record.quota_type === 0) {
  575. // 按量计费
  576. const isTokensDisplay = quotaDisplayType === 'TOKENS';
  577. const inputRatioPriceUSD = record.model_ratio * 2 * usedGroupRatio;
  578. const unitDivisor = tokenUnit === 'K' ? 1000 : 1;
  579. const unitLabel = tokenUnit === 'K' ? 'K' : 'M';
  580. const hasRatioValue = (value) =>
  581. value !== undefined &&
  582. value !== null &&
  583. value !== '' &&
  584. Number.isFinite(Number(value));
  585. const formatRatio = (value) =>
  586. hasRatioValue(value) ? Number(Number(value).toFixed(6)) : null;
  587. if (isTokensDisplay) {
  588. return {
  589. inputRatio: formatRatio(record.model_ratio),
  590. completionRatio: formatRatio(record.completion_ratio),
  591. cacheRatio: formatRatio(record.cache_ratio),
  592. createCacheRatio: formatRatio(record.create_cache_ratio),
  593. imageRatio: formatRatio(record.image_ratio),
  594. audioInputRatio: formatRatio(record.audio_ratio),
  595. audioOutputRatio: formatRatio(record.audio_completion_ratio),
  596. isPerToken: true,
  597. isTokensDisplay: true,
  598. usedGroup,
  599. usedGroupRatio,
  600. };
  601. }
  602. let symbol = '$';
  603. if (currency === 'CNY') {
  604. symbol = '¥';
  605. } else if (currency === 'CUSTOM') {
  606. try {
  607. const statusStr = localStorage.getItem('status');
  608. if (statusStr) {
  609. const s = JSON.parse(statusStr);
  610. symbol = s?.custom_currency_symbol || '¤';
  611. } else {
  612. symbol = '¤';
  613. }
  614. } catch (e) {
  615. symbol = '¤';
  616. }
  617. }
  618. const formatTokenPrice = (priceUSD) => {
  619. const rawDisplayPrice = displayPrice(priceUSD);
  620. const numericPrice =
  621. parseFloat(rawDisplayPrice.replace(/[^0-9.]/g, '')) / unitDivisor;
  622. return `${symbol}${numericPrice.toFixed(precision)}`;
  623. };
  624. const inputPrice = formatTokenPrice(inputRatioPriceUSD);
  625. const audioInputPrice = hasRatioValue(record.audio_ratio)
  626. ? formatTokenPrice(inputRatioPriceUSD * Number(record.audio_ratio))
  627. : null;
  628. return {
  629. inputPrice,
  630. completionPrice: formatTokenPrice(
  631. inputRatioPriceUSD * Number(record.completion_ratio),
  632. ),
  633. cachePrice: hasRatioValue(record.cache_ratio)
  634. ? formatTokenPrice(inputRatioPriceUSD * Number(record.cache_ratio))
  635. : null,
  636. createCachePrice: hasRatioValue(record.create_cache_ratio)
  637. ? formatTokenPrice(inputRatioPriceUSD * Number(record.create_cache_ratio))
  638. : null,
  639. imagePrice: hasRatioValue(record.image_ratio)
  640. ? formatTokenPrice(inputRatioPriceUSD * Number(record.image_ratio))
  641. : null,
  642. audioInputPrice,
  643. audioOutputPrice:
  644. audioInputPrice && hasRatioValue(record.audio_completion_ratio)
  645. ? formatTokenPrice(
  646. inputRatioPriceUSD *
  647. Number(record.audio_ratio) *
  648. Number(record.audio_completion_ratio),
  649. )
  650. : null,
  651. unitLabel,
  652. isPerToken: true,
  653. isTokensDisplay: false,
  654. usedGroup,
  655. usedGroupRatio,
  656. };
  657. }
  658. if (record.quota_type === 1) {
  659. // 按次计费
  660. const priceUSD = parseFloat(record.model_price) * usedGroupRatio;
  661. const displayVal = displayPrice(priceUSD);
  662. return {
  663. price: displayVal,
  664. isPerToken: false,
  665. isTokensDisplay: false,
  666. usedGroup,
  667. usedGroupRatio,
  668. };
  669. }
  670. // 未知计费类型,返回占位信息
  671. return {
  672. price: '-',
  673. isPerToken: false,
  674. isTokensDisplay: false,
  675. usedGroup,
  676. usedGroupRatio,
  677. };
  678. };
  679. export const getModelPriceItems = (
  680. priceData,
  681. t,
  682. quotaDisplayType = 'USD',
  683. ) => {
  684. if (priceData.isDynamicPricing) {
  685. return [
  686. {
  687. key: 'dynamic',
  688. label: t('动态计费'),
  689. value: '',
  690. suffix: '',
  691. isDynamic: true,
  692. },
  693. ];
  694. }
  695. if (priceData.isPerToken) {
  696. if (quotaDisplayType === 'TOKENS' || priceData.isTokensDisplay) {
  697. return [
  698. {
  699. key: 'input-ratio',
  700. label: t('输入倍率'),
  701. value: priceData.inputRatio,
  702. suffix: 'x',
  703. },
  704. {
  705. key: 'completion-ratio',
  706. label: t('补全倍率'),
  707. value: priceData.completionRatio,
  708. suffix: 'x',
  709. },
  710. {
  711. key: 'cache-ratio',
  712. label: t('缓存读取倍率'),
  713. value: priceData.cacheRatio,
  714. suffix: 'x',
  715. },
  716. {
  717. key: 'create-cache-ratio',
  718. label: t('缓存创建倍率'),
  719. value: priceData.createCacheRatio,
  720. suffix: 'x',
  721. },
  722. {
  723. key: 'image-ratio',
  724. label: t('图片输入倍率'),
  725. value: priceData.imageRatio,
  726. suffix: 'x',
  727. },
  728. {
  729. key: 'audio-input-ratio',
  730. label: t('音频输入倍率'),
  731. value: priceData.audioInputRatio,
  732. suffix: 'x',
  733. },
  734. {
  735. key: 'audio-output-ratio',
  736. label: t('音频补全倍率'),
  737. value: priceData.audioOutputRatio,
  738. suffix: 'x',
  739. },
  740. ].filter(
  741. (item) =>
  742. item.value !== null && item.value !== undefined && item.value !== '',
  743. );
  744. }
  745. const unitSuffix = ` / 1${priceData.unitLabel} Tokens`;
  746. return [
  747. {
  748. key: 'input',
  749. label: t('输入价格'),
  750. value: priceData.inputPrice,
  751. suffix: unitSuffix,
  752. },
  753. {
  754. key: 'completion',
  755. label: t('补全价格'),
  756. value: priceData.completionPrice,
  757. suffix: unitSuffix,
  758. },
  759. {
  760. key: 'cache',
  761. label: t('缓存读取价格'),
  762. value: priceData.cachePrice,
  763. suffix: unitSuffix,
  764. },
  765. {
  766. key: 'create-cache',
  767. label: t('缓存创建价格'),
  768. value: priceData.createCachePrice,
  769. suffix: unitSuffix,
  770. },
  771. {
  772. key: 'image',
  773. label: t('图片输入价格'),
  774. value: priceData.imagePrice,
  775. suffix: unitSuffix,
  776. },
  777. {
  778. key: 'audio-input',
  779. label: t('音频输入价格'),
  780. value: priceData.audioInputPrice,
  781. suffix: unitSuffix,
  782. },
  783. {
  784. key: 'audio-output',
  785. label: t('音频补全价格'),
  786. value: priceData.audioOutputPrice,
  787. suffix: unitSuffix,
  788. },
  789. ].filter((item) => item.value !== null && item.value !== undefined && item.value !== '');
  790. }
  791. return [
  792. {
  793. key: 'fixed',
  794. label: t('模型价格'),
  795. value: priceData.price,
  796. suffix: ` / ${t('次')}`,
  797. },
  798. ].filter((item) => item.value !== null && item.value !== undefined && item.value !== '');
  799. };
  800. // 格式化动态计费摘要(用于卡片视图,与 formatPriceInfo 风格统一)
  801. export const formatDynamicPriceSummary = (billingExpr, t, groupRatio = 1) => {
  802. if (!billingExpr) return <span style={{ color: 'var(--semi-color-text-1)' }}>{t('动态计费')}</span>;
  803. const gr = groupRatio || 1;
  804. const tierMatches = billingExpr.match(/tier\(/g) || [];
  805. const tierCount = tierMatches.length;
  806. const varCoeffs = {};
  807. const varRe = /\b(p|c|cr|cc|cc1h|img|ai|ao)\s*\*\s*([\d.eE+-]+)/g;
  808. let vm;
  809. while ((vm = varRe.exec(billingExpr)) !== null) {
  810. if (!(vm[1] in varCoeffs)) varCoeffs[vm[1]] = Number(vm[2]);
  811. }
  812. const hasCoeffs = 'p' in varCoeffs || 'c' in varCoeffs;
  813. const varLabels = [
  814. ['p', '输入价格'],
  815. ['c', '补全价格'],
  816. ['cr', '缓存读取价格'],
  817. ['cc', '缓存创建价格'],
  818. ['cc1h', '1h缓存创建价格'],
  819. ['img', '图片输入价格'],
  820. ['ai', '音频输入价格'],
  821. ['ao', '音频输出价格'],
  822. ];
  823. const hasTimeCondition = /\b(?:hour|weekday|month|day)\(/.test(billingExpr);
  824. const hasRequestCondition = /\b(?:param|header)\(/.test(billingExpr);
  825. const tags = [];
  826. if (tierCount > 1) tags.push(`${tierCount}${t('档')}`);
  827. if (hasTimeCondition) tags.push(t('含时间条件'));
  828. if (hasRequestCondition) tags.push(t('含请求条件'));
  829. const unitSuffix = ' / 1M Tokens';
  830. const lineStyle = { color: 'var(--semi-color-text-1)' };
  831. return (
  832. <>
  833. {hasCoeffs && (
  834. <>
  835. {varLabels.map(([key, label]) =>
  836. key in varCoeffs ? (
  837. <span key={key} style={lineStyle}>
  838. {t(label)} ${(varCoeffs[key] * gr).toFixed(4)}{unitSuffix}
  839. </span>
  840. ) : null,
  841. )}
  842. </>
  843. )}
  844. {(tierCount > 1 || hasTimeCondition || hasRequestCondition) && (
  845. <span style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
  846. <span
  847. style={{
  848. display: 'inline-block',
  849. padding: '1px 6px',
  850. borderRadius: 4,
  851. fontSize: 11,
  852. background: 'var(--semi-color-warning-light-default)',
  853. color: 'var(--semi-color-warning)',
  854. }}
  855. >
  856. {t('动态计费')}
  857. </span>
  858. {tags.map((tag) => (
  859. <span
  860. key={tag}
  861. style={{
  862. display: 'inline-block',
  863. padding: '1px 6px',
  864. borderRadius: 4,
  865. fontSize: 11,
  866. background: 'var(--semi-color-fill-1)',
  867. color: 'var(--semi-color-text-2)',
  868. }}
  869. >
  870. {tag}
  871. </span>
  872. ))}
  873. </span>
  874. )}
  875. </>
  876. );
  877. };
  878. // 格式化价格信息(用于卡片视图)
  879. export const formatPriceInfo = (priceData, t, quotaDisplayType = 'USD') => {
  880. const items = getModelPriceItems(priceData, t, quotaDisplayType);
  881. return (
  882. <>
  883. {items.map((item) => (
  884. <span key={item.key} style={{ color: 'var(--semi-color-text-1)' }}>
  885. {item.label} {item.value}
  886. {item.suffix}
  887. </span>
  888. ))}
  889. </>
  890. );
  891. };
  892. // -------------------------------
  893. // CardPro 分页配置函数
  894. // 用于创建 CardPro 的 paginationArea 配置
  895. export const createCardProPagination = ({
  896. currentPage,
  897. pageSize,
  898. total,
  899. onPageChange,
  900. onPageSizeChange,
  901. isMobile = false,
  902. pageSizeOpts = [10, 20, 50, 100],
  903. showSizeChanger = true,
  904. t = (key) => key,
  905. }) => {
  906. if (!total || total <= 0) return null;
  907. const start = (currentPage - 1) * pageSize + 1;
  908. const end = Math.min(currentPage * pageSize, total);
  909. const totalText = `${t('显示第')} ${start} ${t('条 - 第')} ${end} ${t('条,共')} ${total} ${t('条')}`;
  910. return (
  911. <>
  912. {/* 桌面端左侧总数信息 */}
  913. {!isMobile && (
  914. <span
  915. className='text-sm select-none'
  916. style={{ color: 'var(--semi-color-text-2)' }}
  917. >
  918. {totalText}
  919. </span>
  920. )}
  921. {/* 右侧分页控件 */}
  922. <Pagination
  923. currentPage={currentPage}
  924. pageSize={pageSize}
  925. total={total}
  926. pageSizeOpts={pageSizeOpts}
  927. showSizeChanger={showSizeChanger}
  928. onPageSizeChange={onPageSizeChange}
  929. onPageChange={onPageChange}
  930. size={isMobile ? 'small' : 'default'}
  931. showQuickJumper={isMobile}
  932. showTotal
  933. />
  934. </>
  935. );
  936. };
  937. // 模型定价筛选条件默认值
  938. const DEFAULT_PRICING_FILTERS = {
  939. search: '',
  940. showWithRecharge: false,
  941. currency: 'USD',
  942. showRatio: false,
  943. viewMode: 'card',
  944. tokenUnit: 'M',
  945. filterGroup: 'all',
  946. filterQuotaType: 'all',
  947. filterEndpointType: 'all',
  948. filterVendor: 'all',
  949. filterTag: 'all',
  950. currentPage: 1,
  951. };
  952. // 重置模型定价筛选条件
  953. export const resetPricingFilters = ({
  954. handleChange,
  955. setShowWithRecharge,
  956. setCurrency,
  957. setShowRatio,
  958. setViewMode,
  959. setFilterGroup,
  960. setFilterQuotaType,
  961. setFilterEndpointType,
  962. setFilterVendor,
  963. setFilterTag,
  964. setCurrentPage,
  965. setTokenUnit,
  966. }) => {
  967. handleChange?.(DEFAULT_PRICING_FILTERS.search);
  968. setShowWithRecharge?.(DEFAULT_PRICING_FILTERS.showWithRecharge);
  969. setCurrency?.(DEFAULT_PRICING_FILTERS.currency);
  970. setShowRatio?.(DEFAULT_PRICING_FILTERS.showRatio);
  971. setViewMode?.(DEFAULT_PRICING_FILTERS.viewMode);
  972. setTokenUnit?.(DEFAULT_PRICING_FILTERS.tokenUnit);
  973. setFilterGroup?.(DEFAULT_PRICING_FILTERS.filterGroup);
  974. setFilterQuotaType?.(DEFAULT_PRICING_FILTERS.filterQuotaType);
  975. setFilterEndpointType?.(DEFAULT_PRICING_FILTERS.filterEndpointType);
  976. setFilterVendor?.(DEFAULT_PRICING_FILTERS.filterVendor);
  977. setFilterTag?.(DEFAULT_PRICING_FILTERS.filterTag);
  978. setCurrentPage?.(DEFAULT_PRICING_FILTERS.currentPage);
  979. };