25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

2323 satır
70 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 i18next from 'i18next';
  16. import { Modal, Tag, Typography, Avatar } from '@douyinfe/semi-ui';
  17. import { copy, showSuccess } from './utils';
  18. import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
  19. import { visit } from 'unist-util-visit';
  20. import * as LobeIcons from '@lobehub/icons';
  21. import {
  22. OpenAI,
  23. Claude,
  24. Gemini,
  25. Moonshot,
  26. Zhipu,
  27. Qwen,
  28. DeepSeek,
  29. Minimax,
  30. Wenxin,
  31. Spark,
  32. Midjourney,
  33. Hunyuan,
  34. Cohere,
  35. Cloudflare,
  36. Ai360,
  37. Yi,
  38. Jina,
  39. Mistral,
  40. XAI,
  41. Ollama,
  42. Doubao,
  43. Suno,
  44. Xinference,
  45. OpenRouter,
  46. Dify,
  47. Coze,
  48. SiliconCloud,
  49. FastGPT,
  50. Kling,
  51. Jimeng,
  52. Perplexity,
  53. Replicate,
  54. } from '@lobehub/icons';
  55. import {
  56. LayoutDashboard,
  57. TerminalSquare,
  58. MessageSquare,
  59. Key,
  60. BarChart3,
  61. Image as ImageIcon,
  62. CheckSquare,
  63. CreditCard,
  64. Layers,
  65. Gift,
  66. User,
  67. Settings,
  68. CircleUser,
  69. Package,
  70. Server,
  71. CalendarClock,
  72. } from 'lucide-react';
  73. import {
  74. SiAtlassian,
  75. SiAuth0,
  76. SiAuthentik,
  77. SiBitbucket,
  78. SiDiscord,
  79. SiDropbox,
  80. SiFacebook,
  81. SiGitea,
  82. SiGithub,
  83. SiGitlab,
  84. SiGoogle,
  85. SiKeycloak,
  86. SiNextcloud,
  87. SiNotion,
  88. SiOkta,
  89. SiOpenid,
  90. SiReddit,
  91. SiSlack,
  92. SiTelegram,
  93. SiTwitch,
  94. SiWechat,
  95. SiX,
  96. } from 'react-icons/si';
  97. // 获取侧边栏Lucide图标组件
  98. export function getLucideIcon(key, selected = false) {
  99. const size = 16;
  100. const strokeWidth = 2;
  101. const SELECTED_COLOR = 'var(--semi-color-primary)';
  102. const iconColor = selected ? SELECTED_COLOR : 'currentColor';
  103. const commonProps = {
  104. size,
  105. strokeWidth,
  106. className: `transition-colors duration-200 ${selected ? 'transition-transform duration-200 scale-105' : ''}`,
  107. };
  108. // 根据不同的key返回不同的图标
  109. switch (key) {
  110. case 'detail':
  111. return <LayoutDashboard {...commonProps} color={iconColor} />;
  112. case 'playground':
  113. return <TerminalSquare {...commonProps} color={iconColor} />;
  114. case 'chat':
  115. return <MessageSquare {...commonProps} color={iconColor} />;
  116. case 'token':
  117. return <Key {...commonProps} color={iconColor} />;
  118. case 'log':
  119. return <BarChart3 {...commonProps} color={iconColor} />;
  120. case 'midjourney':
  121. return <ImageIcon {...commonProps} color={iconColor} />;
  122. case 'task':
  123. return <CheckSquare {...commonProps} color={iconColor} />;
  124. case 'topup':
  125. return <CreditCard {...commonProps} color={iconColor} />;
  126. case 'channel':
  127. return <Layers {...commonProps} color={iconColor} />;
  128. case 'redemption':
  129. return <Gift {...commonProps} color={iconColor} />;
  130. case 'user':
  131. case 'personal':
  132. return <User {...commonProps} color={iconColor} />;
  133. case 'models':
  134. return <Package {...commonProps} color={iconColor} />;
  135. case 'deployment':
  136. return <Server {...commonProps} color={iconColor} />;
  137. case 'subscription':
  138. return <CalendarClock {...commonProps} color={iconColor} />;
  139. case 'setting':
  140. return <Settings {...commonProps} color={iconColor} />;
  141. default:
  142. return <CircleUser {...commonProps} color={iconColor} />;
  143. }
  144. }
  145. // 获取模型分类
  146. export const getModelCategories = (() => {
  147. let categoriesCache = null;
  148. let lastLocale = null;
  149. return (t) => {
  150. const currentLocale = i18next.language;
  151. if (categoriesCache && lastLocale === currentLocale) {
  152. return categoriesCache;
  153. }
  154. categoriesCache = {
  155. all: {
  156. label: t('全部模型'),
  157. icon: null,
  158. filter: () => true,
  159. },
  160. openai: {
  161. label: 'OpenAI',
  162. icon: <OpenAI />,
  163. filter: (model) =>
  164. model.model_name.toLowerCase().includes('gpt') ||
  165. model.model_name.toLowerCase().includes('dall-e') ||
  166. model.model_name.toLowerCase().includes('whisper') ||
  167. model.model_name.toLowerCase().includes('tts-1') ||
  168. model.model_name.toLowerCase().includes('text-embedding-3') ||
  169. model.model_name.toLowerCase().includes('text-moderation') ||
  170. model.model_name.toLowerCase().includes('babbage') ||
  171. model.model_name.toLowerCase().includes('davinci') ||
  172. model.model_name.toLowerCase().includes('curie') ||
  173. model.model_name.toLowerCase().includes('ada') ||
  174. model.model_name.toLowerCase().includes('o1') ||
  175. model.model_name.toLowerCase().includes('o3') ||
  176. model.model_name.toLowerCase().includes('o4'),
  177. },
  178. anthropic: {
  179. label: 'Anthropic',
  180. icon: <Claude.Color />,
  181. filter: (model) => model.model_name.toLowerCase().includes('claude'),
  182. },
  183. gemini: {
  184. label: 'Gemini',
  185. icon: <Gemini.Color />,
  186. filter: (model) =>
  187. model.model_name.toLowerCase().includes('gemini') ||
  188. model.model_name.toLowerCase().includes('gemma') ||
  189. model.model_name.toLowerCase().includes('learnlm') ||
  190. model.model_name.toLowerCase().startsWith('embedding-') ||
  191. model.model_name.toLowerCase().includes('text-embedding-004') ||
  192. model.model_name.toLowerCase().includes('imagen-4') ||
  193. model.model_name.toLowerCase().includes('veo-') ||
  194. model.model_name.toLowerCase().includes('aqa'),
  195. },
  196. moonshot: {
  197. label: 'Moonshot',
  198. icon: <Moonshot />,
  199. filter: (model) =>
  200. model.model_name.toLowerCase().includes('moonshot') ||
  201. model.model_name.toLowerCase().includes('kimi'),
  202. },
  203. zhipu: {
  204. label: t('智谱'),
  205. icon: <Zhipu.Color />,
  206. filter: (model) =>
  207. model.model_name.toLowerCase().includes('chatglm') ||
  208. model.model_name.toLowerCase().includes('glm-') ||
  209. model.model_name.toLowerCase().includes('cogview') ||
  210. model.model_name.toLowerCase().includes('cogvideo'),
  211. },
  212. qwen: {
  213. label: t('通义千问'),
  214. icon: <Qwen.Color />,
  215. filter: (model) => model.model_name.toLowerCase().includes('qwen'),
  216. },
  217. deepseek: {
  218. label: 'DeepSeek',
  219. icon: <DeepSeek.Color />,
  220. filter: (model) => model.model_name.toLowerCase().includes('deepseek'),
  221. },
  222. minimax: {
  223. label: 'MiniMax',
  224. icon: <Minimax.Color />,
  225. filter: (model) =>
  226. model.model_name.toLowerCase().includes('abab') ||
  227. model.model_name.toLowerCase().includes('minimax'),
  228. },
  229. baidu: {
  230. label: t('文心一言'),
  231. icon: <Wenxin.Color />,
  232. filter: (model) => model.model_name.toLowerCase().includes('ernie'),
  233. },
  234. xunfei: {
  235. label: t('讯飞星火'),
  236. icon: <Spark.Color />,
  237. filter: (model) => model.model_name.toLowerCase().includes('spark'),
  238. },
  239. midjourney: {
  240. label: 'Midjourney',
  241. icon: <Midjourney />,
  242. filter: (model) => model.model_name.toLowerCase().includes('mj_'),
  243. },
  244. tencent: {
  245. label: t('腾讯混元'),
  246. icon: <Hunyuan.Color />,
  247. filter: (model) => model.model_name.toLowerCase().includes('hunyuan'),
  248. },
  249. cohere: {
  250. label: 'Cohere',
  251. icon: <Cohere.Color />,
  252. filter: (model) =>
  253. model.model_name.toLowerCase().includes('command') ||
  254. model.model_name.toLowerCase().includes('c4ai-') ||
  255. model.model_name.toLowerCase().includes('embed-'),
  256. },
  257. cloudflare: {
  258. label: 'Cloudflare',
  259. icon: <Cloudflare.Color />,
  260. filter: (model) => model.model_name.toLowerCase().includes('@cf/'),
  261. },
  262. ai360: {
  263. label: t('360智脑'),
  264. icon: <Ai360.Color />,
  265. filter: (model) => model.model_name.toLowerCase().includes('360'),
  266. },
  267. jina: {
  268. label: 'Jina',
  269. icon: <Jina />,
  270. filter: (model) => model.model_name.toLowerCase().includes('jina'),
  271. },
  272. mistral: {
  273. label: 'Mistral AI',
  274. icon: <Mistral.Color />,
  275. filter: (model) =>
  276. model.model_name.toLowerCase().includes('mistral') ||
  277. model.model_name.toLowerCase().includes('codestral') ||
  278. model.model_name.toLowerCase().includes('pixtral') ||
  279. model.model_name.toLowerCase().includes('voxtral') ||
  280. model.model_name.toLowerCase().includes('magistral'),
  281. },
  282. xai: {
  283. label: 'xAI',
  284. icon: <XAI />,
  285. filter: (model) => model.model_name.toLowerCase().includes('grok'),
  286. },
  287. llama: {
  288. label: 'Llama',
  289. icon: <Ollama />,
  290. filter: (model) => model.model_name.toLowerCase().includes('llama'),
  291. },
  292. doubao: {
  293. label: t('豆包'),
  294. icon: <Doubao.Color />,
  295. filter: (model) => model.model_name.toLowerCase().includes('doubao'),
  296. },
  297. yi: {
  298. label: t('零一万物'),
  299. icon: <Yi.Color />,
  300. filter: (model) => model.model_name.toLowerCase().includes('yi'),
  301. },
  302. };
  303. lastLocale = currentLocale;
  304. return categoriesCache;
  305. };
  306. })();
  307. /**
  308. * 根据渠道类型返回对应的厂商图标
  309. * @param {number} channelType - 渠道类型值
  310. * @returns {JSX.Element|null} - 对应的厂商图标组件
  311. */
  312. export function getChannelIcon(channelType) {
  313. const iconSize = 14;
  314. switch (channelType) {
  315. case 1: // OpenAI
  316. case 3: // Azure OpenAI
  317. case 57: // Codex
  318. return <OpenAI size={iconSize} />;
  319. case 2: // Midjourney Proxy
  320. case 5: // Midjourney Proxy Plus
  321. return <Midjourney size={iconSize} />;
  322. case 36: // Suno API
  323. return <Suno size={iconSize} />;
  324. case 4: // Ollama
  325. return <Ollama size={iconSize} />;
  326. case 14: // Anthropic Claude
  327. case 33: // AWS Claude
  328. return <Claude.Color size={iconSize} />;
  329. case 41: // Vertex AI
  330. return <Gemini.Color size={iconSize} />;
  331. case 34: // Cohere
  332. return <Cohere.Color size={iconSize} />;
  333. case 39: // Cloudflare
  334. return <Cloudflare.Color size={iconSize} />;
  335. case 43: // DeepSeek
  336. return <DeepSeek.Color size={iconSize} />;
  337. case 15: // 百度文心千帆
  338. case 46: // 百度文心千帆V2
  339. return <Wenxin.Color size={iconSize} />;
  340. case 17: // 阿里通义千问
  341. return <Qwen.Color size={iconSize} />;
  342. case 18: // 讯飞星火认知
  343. return <Spark.Color size={iconSize} />;
  344. case 16: // 智谱 ChatGLM
  345. case 26: // 智谱 GLM-4V
  346. return <Zhipu.Color size={iconSize} />;
  347. case 24: // Google Gemini
  348. case 11: // Google PaLM2
  349. return <Gemini.Color size={iconSize} />;
  350. case 47: // Xinference
  351. return <Xinference.Color size={iconSize} />;
  352. case 25: // Moonshot
  353. return <Moonshot size={iconSize} />;
  354. case 27: // Perplexity
  355. return <Perplexity.Color size={iconSize} />;
  356. case 20: // OpenRouter
  357. return <OpenRouter size={iconSize} />;
  358. case 19: // 360 智脑
  359. return <Ai360.Color size={iconSize} />;
  360. case 23: // 腾讯混元
  361. return <Hunyuan.Color size={iconSize} />;
  362. case 31: // 零一万物
  363. return <Yi.Color size={iconSize} />;
  364. case 35: // MiniMax
  365. return <Minimax.Color size={iconSize} />;
  366. case 37: // Dify
  367. return <Dify.Color size={iconSize} />;
  368. case 38: // Jina
  369. return <Jina size={iconSize} />;
  370. case 40: // SiliconCloud
  371. return <SiliconCloud.Color size={iconSize} />;
  372. case 42: // Mistral AI
  373. return <Mistral.Color size={iconSize} />;
  374. case 45: // 字节火山方舟、豆包通用
  375. return <Doubao.Color size={iconSize} />;
  376. case 48: // xAI
  377. return <XAI size={iconSize} />;
  378. case 49: // Coze
  379. return <Coze size={iconSize} />;
  380. case 50: // 可灵 Kling
  381. return <Kling.Color size={iconSize} />;
  382. case 51: // 即梦 Jimeng
  383. return <Jimeng.Color size={iconSize} />;
  384. case 54: // 豆包视频 Doubao Video
  385. return <Doubao.Color size={iconSize} />;
  386. case 56: // Replicate
  387. return <Replicate size={iconSize} />;
  388. case 8: // 自定义渠道
  389. case 22: // 知识库:FastGPT
  390. return <FastGPT.Color size={iconSize} />;
  391. case 21: // 知识库:AI Proxy
  392. case 44: // 嵌入模型:MokaAI M3E
  393. default:
  394. return null; // 未知类型或自定义渠道不显示图标
  395. }
  396. }
  397. /**
  398. * 根据图标名称动态获取 LobeHub 图标组件
  399. * 支持:
  400. * - 基础:"OpenAI"、"OpenAI.Color" 等
  401. * - 额外属性(点号链式):"OpenAI.Avatar.type={'platform'}"、"OpenRouter.Avatar.shape={'square'}"
  402. * - 继续兼容第二参数 size;若字符串里有 size=,以字符串为准
  403. * @param {string} iconName - 图标名称/描述
  404. * @param {number} size - 图标大小,默认为 14
  405. * @returns {JSX.Element} - 对应的图标组件或 Avatar
  406. */
  407. export function getLobeHubIcon(iconName, size = 14) {
  408. if (typeof iconName === 'string') iconName = iconName.trim();
  409. // 如果没有图标名称,返回 Avatar
  410. if (!iconName) {
  411. return <Avatar size='extra-extra-small'>?</Avatar>;
  412. }
  413. // 解析组件路径与点号链式属性
  414. const segments = String(iconName).split('.');
  415. const baseKey = segments[0];
  416. const BaseIcon = LobeIcons[baseKey];
  417. let IconComponent = undefined;
  418. let propStartIndex = 1;
  419. if (BaseIcon && segments.length > 1 && BaseIcon[segments[1]]) {
  420. IconComponent = BaseIcon[segments[1]];
  421. propStartIndex = 2;
  422. } else {
  423. IconComponent = LobeIcons[baseKey];
  424. propStartIndex = 1;
  425. }
  426. // 失败兜底
  427. if (
  428. !IconComponent ||
  429. (typeof IconComponent !== 'function' && typeof IconComponent !== 'object')
  430. ) {
  431. const firstLetter = String(iconName).charAt(0).toUpperCase();
  432. return <Avatar size='extra-extra-small'>{firstLetter}</Avatar>;
  433. }
  434. // 解析点号链式属性,形如:key={...}、key='...'、key="..."、key=123、key、key=true/false
  435. const props = {};
  436. const parseValue = (raw) => {
  437. if (raw == null) return true;
  438. let v = String(raw).trim();
  439. // 去除一层花括号包裹
  440. if (v.startsWith('{') && v.endsWith('}')) {
  441. v = v.slice(1, -1).trim();
  442. }
  443. // 去除引号
  444. if (
  445. (v.startsWith('"') && v.endsWith('"')) ||
  446. (v.startsWith("'") && v.endsWith("'"))
  447. ) {
  448. return v.slice(1, -1);
  449. }
  450. // 布尔
  451. if (v === 'true') return true;
  452. if (v === 'false') return false;
  453. // 数字
  454. if (/^-?\d+(?:\.\d+)?$/.test(v)) return Number(v);
  455. // 其他原样返回字符串
  456. return v;
  457. };
  458. for (let i = propStartIndex; i < segments.length; i++) {
  459. const seg = segments[i];
  460. if (!seg) continue;
  461. const eqIdx = seg.indexOf('=');
  462. if (eqIdx === -1) {
  463. props[seg.trim()] = true;
  464. continue;
  465. }
  466. const key = seg.slice(0, eqIdx).trim();
  467. const valRaw = seg.slice(eqIdx + 1).trim();
  468. props[key] = parseValue(valRaw);
  469. }
  470. // 兼容第二参数 size,若字符串中未显式指定 size,则使用函数入参
  471. if (props.size == null && size != null) props.size = size;
  472. return <IconComponent {...props} />;
  473. }
  474. const oauthProviderIconMap = {
  475. github: SiGithub,
  476. gitlab: SiGitlab,
  477. gitea: SiGitea,
  478. google: SiGoogle,
  479. discord: SiDiscord,
  480. facebook: SiFacebook,
  481. x: SiX,
  482. twitter: SiX,
  483. slack: SiSlack,
  484. telegram: SiTelegram,
  485. wechat: SiWechat,
  486. keycloak: SiKeycloak,
  487. nextcloud: SiNextcloud,
  488. authentik: SiAuthentik,
  489. openid: SiOpenid,
  490. okta: SiOkta,
  491. auth0: SiAuth0,
  492. atlassian: SiAtlassian,
  493. bitbucket: SiBitbucket,
  494. notion: SiNotion,
  495. twitch: SiTwitch,
  496. reddit: SiReddit,
  497. dropbox: SiDropbox,
  498. };
  499. function isHttpUrl(value) {
  500. return /^https?:\/\//i.test(value || '');
  501. }
  502. function isSimpleEmoji(value) {
  503. if (!value) return false;
  504. const trimmed = String(value).trim();
  505. return trimmed.length > 0 && trimmed.length <= 4 && !isHttpUrl(trimmed);
  506. }
  507. function normalizeOAuthIconKey(raw) {
  508. return raw
  509. .trim()
  510. .toLowerCase()
  511. .replace(/^ri:/, '')
  512. .replace(/^react-icons:/, '')
  513. .replace(/^si:/, '');
  514. }
  515. /**
  516. * Render custom OAuth provider icon with react-icons or URL/emoji fallback.
  517. * Supported formats:
  518. * - react-icons simple key: github / gitlab / google / keycloak
  519. * - prefixed key: ri:github / si:github
  520. * - full URL image: https://example.com/logo.png
  521. * - emoji: 🐱
  522. */
  523. export function getOAuthProviderIcon(iconName, size = 20) {
  524. const raw = String(iconName || '').trim();
  525. const iconSize = Number(size) > 0 ? Number(size) : 20;
  526. if (!raw) {
  527. return <Layers size={iconSize} color='var(--semi-color-text-2)' />;
  528. }
  529. if (isHttpUrl(raw)) {
  530. return (
  531. <img
  532. src={raw}
  533. alt='provider icon'
  534. width={iconSize}
  535. height={iconSize}
  536. style={{ borderRadius: 4, objectFit: 'cover' }}
  537. />
  538. );
  539. }
  540. if (isSimpleEmoji(raw)) {
  541. return (
  542. <span
  543. style={{
  544. width: iconSize,
  545. height: iconSize,
  546. lineHeight: `${iconSize}px`,
  547. textAlign: 'center',
  548. display: 'inline-block',
  549. fontSize: Math.max(Math.floor(iconSize * 0.8), 14),
  550. }}
  551. >
  552. {raw}
  553. </span>
  554. );
  555. }
  556. const key = normalizeOAuthIconKey(raw);
  557. const IconComp = oauthProviderIconMap[key];
  558. if (IconComp) {
  559. return <IconComp size={iconSize} />;
  560. }
  561. return <Avatar size='extra-extra-small'>{raw.charAt(0).toUpperCase()}</Avatar>;
  562. }
  563. // 颜色列表
  564. const colors = [
  565. 'amber',
  566. 'blue',
  567. 'cyan',
  568. 'green',
  569. 'grey',
  570. 'indigo',
  571. 'light-blue',
  572. 'lime',
  573. 'orange',
  574. 'pink',
  575. 'purple',
  576. 'red',
  577. 'teal',
  578. 'violet',
  579. 'yellow',
  580. ];
  581. // 基础10色色板 (N ≤ 10)
  582. const baseColors = [
  583. '#1664FF', // 主色
  584. '#1AC6FF',
  585. '#FF8A00',
  586. '#3CC780',
  587. '#7442D4',
  588. '#FFC400',
  589. '#304D77',
  590. '#B48DEB',
  591. '#009488',
  592. '#FF7DDA',
  593. ];
  594. // 扩展20色色板 (10 < N ≤ 20)
  595. const extendedColors = [
  596. '#1664FF',
  597. '#B2CFFF',
  598. '#1AC6FF',
  599. '#94EFFF',
  600. '#FF8A00',
  601. '#FFCE7A',
  602. '#3CC780',
  603. '#B9EDCD',
  604. '#7442D4',
  605. '#DDC5FA',
  606. '#FFC400',
  607. '#FAE878',
  608. '#304D77',
  609. '#8B959E',
  610. '#B48DEB',
  611. '#EFE3FF',
  612. '#009488',
  613. '#59BAA8',
  614. '#FF7DDA',
  615. '#FFCFEE',
  616. ];
  617. // 模型颜色映射
  618. export const modelColorMap = {
  619. 'dall-e': 'rgb(147,112,219)', // 深紫色
  620. // 'dall-e-2': 'rgb(147,112,219)', // 介于紫色和蓝色之间的色调
  621. 'dall-e-3': 'rgb(153,50,204)', // 介于紫罗兰和洋红之间的色调
  622. 'gpt-3.5-turbo': 'rgb(184,227,167)', // 浅绿色
  623. // 'gpt-3.5-turbo-0301': 'rgb(131,220,131)', // 亮绿色
  624. 'gpt-3.5-turbo-0613': 'rgb(60,179,113)', // 海洋绿
  625. 'gpt-3.5-turbo-1106': 'rgb(32,178,170)', // 浅海洋绿
  626. 'gpt-3.5-turbo-16k': 'rgb(149,252,206)', // 淡橙色
  627. 'gpt-3.5-turbo-16k-0613': 'rgb(119,255,214)', // 淡桃
  628. 'gpt-3.5-turbo-instruct': 'rgb(175,238,238)', // 粉蓝色
  629. 'gpt-4': 'rgb(135,206,235)', // 天蓝色
  630. // 'gpt-4-0314': 'rgb(70,130,180)', // 钢蓝色
  631. 'gpt-4-0613': 'rgb(100,149,237)', // 矢车菊蓝
  632. 'gpt-4-1106-preview': 'rgb(30,144,255)', // 道奇蓝
  633. 'gpt-4-0125-preview': 'rgb(2,177,236)', // 深天蓝
  634. 'gpt-4-turbo-preview': 'rgb(2,177,255)', // 深天蓝
  635. 'gpt-4-32k': 'rgb(104,111,238)', // 中紫色
  636. // 'gpt-4-32k-0314': 'rgb(90,105,205)', // 暗灰蓝色
  637. 'gpt-4-32k-0613': 'rgb(61,71,139)', // 暗蓝灰色
  638. 'gpt-4-all': 'rgb(65,105,225)', // 皇家蓝
  639. 'gpt-4-gizmo-*': 'rgb(0,0,255)', // 纯蓝色
  640. 'gpt-4-vision-preview': 'rgb(25,25,112)', // 午夜蓝
  641. 'text-ada-001': 'rgb(255,192,203)', // 粉红色
  642. 'text-babbage-001': 'rgb(255,160,122)', // 浅珊瑚色
  643. 'text-curie-001': 'rgb(219,112,147)', // 苍紫罗兰色
  644. // 'text-davinci-002': 'rgb(199,21,133)', // 中紫罗兰红色
  645. 'text-davinci-003': 'rgb(219,112,147)', // 苍紫罗兰色(与Curie相同,表示同一个系列)
  646. 'text-davinci-edit-001': 'rgb(255,105,180)', // 热粉色
  647. 'text-embedding-ada-002': 'rgb(255,182,193)', // 浅粉红
  648. 'text-embedding-v1': 'rgb(255,174,185)', // 浅粉红色(略有区别)
  649. 'text-moderation-latest': 'rgb(255,130,171)', // 强粉色
  650. 'text-moderation-stable': 'rgb(255,160,122)', // 浅珊瑚色(与Babbage相同,表示同一类功能)
  651. 'tts-1': 'rgb(255,140,0)', // 深橙色
  652. 'tts-1-1106': 'rgb(255,165,0)', // 橙色
  653. 'tts-1-hd': 'rgb(255,215,0)', // 金色
  654. 'tts-1-hd-1106': 'rgb(255,223,0)', // 金黄色(略有区别)
  655. 'whisper-1': 'rgb(245,245,220)', // 米色
  656. 'claude-3-opus-20240229': 'rgb(255,132,31)', // 橙红色
  657. 'claude-3-sonnet-20240229': 'rgb(253,135,93)', // 橙色
  658. 'claude-3-haiku-20240307': 'rgb(255,175,146)', // 浅橙色
  659. };
  660. export function modelToColor(modelName) {
  661. // 1. 如果模型在预定义的 modelColorMap 中,使用预定义颜色
  662. if (modelColorMap[modelName]) {
  663. return modelColorMap[modelName];
  664. }
  665. // 2. 生成一个稳定的数字作为索引
  666. let hash = 0;
  667. for (let i = 0; i < modelName.length; i++) {
  668. hash = (hash << 5) - hash + modelName.charCodeAt(i);
  669. hash = hash & hash; // Convert to 32-bit integer
  670. }
  671. hash = Math.abs(hash);
  672. // 3. 根据模型名称长度选择不同的色板
  673. const colorPalette = modelName.length > 10 ? extendedColors : baseColors;
  674. // 4. 使用hash值选择颜色
  675. const index = hash % colorPalette.length;
  676. return colorPalette[index];
  677. }
  678. export function stringToColor(str) {
  679. let sum = 0;
  680. for (let i = 0; i < str.length; i++) {
  681. sum += str.charCodeAt(i);
  682. }
  683. let i = sum % colors.length;
  684. return colors[i];
  685. }
  686. // 渲染带有模型图标的标签
  687. export function renderModelTag(modelName, options = {}) {
  688. const {
  689. color,
  690. size = 'default',
  691. shape = 'circle',
  692. onClick,
  693. suffixIcon,
  694. } = options;
  695. const categories = getModelCategories(i18next.t);
  696. let icon = null;
  697. for (const [key, category] of Object.entries(categories)) {
  698. if (key !== 'all' && category.filter({ model_name: modelName })) {
  699. icon = category.icon;
  700. break;
  701. }
  702. }
  703. return (
  704. <Tag
  705. color={color || stringToColor(modelName)}
  706. prefixIcon={icon}
  707. suffixIcon={suffixIcon}
  708. size={size}
  709. shape={shape}
  710. onClick={onClick}
  711. >
  712. {modelName}
  713. </Tag>
  714. );
  715. }
  716. export function renderText(text, limit) {
  717. if (text.length > limit) {
  718. return text.slice(0, limit - 3) + '...';
  719. }
  720. return text;
  721. }
  722. /**
  723. * Render group tags based on the input group string
  724. * @param {string} group - The input group string
  725. * @returns {JSX.Element} - The rendered group tags
  726. */
  727. export function renderGroup(group) {
  728. if (group === '') {
  729. return (
  730. <Tag key='default' color='white' shape='circle'>
  731. {i18next.t('用户分组')}
  732. </Tag>
  733. );
  734. }
  735. const tagColors = {
  736. vip: 'yellow',
  737. pro: 'yellow',
  738. svip: 'red',
  739. premium: 'red',
  740. };
  741. const groups = group.split(',').sort();
  742. return (
  743. <span key={group}>
  744. {groups.map((group) => (
  745. <Tag
  746. color={tagColors[group] || stringToColor(group)}
  747. key={group}
  748. shape='circle'
  749. onClick={async (event) => {
  750. event.stopPropagation();
  751. if (await copy(group)) {
  752. showSuccess(i18next.t('已复制:') + group);
  753. } else {
  754. Modal.error({
  755. title: i18next.t('无法复制到剪贴板,请手动复制'),
  756. content: group,
  757. });
  758. }
  759. }}
  760. >
  761. {group}
  762. </Tag>
  763. ))}
  764. </span>
  765. );
  766. }
  767. export function renderRatio(ratio) {
  768. let color = 'green';
  769. if (ratio > 5) {
  770. color = 'red';
  771. } else if (ratio > 3) {
  772. color = 'orange';
  773. } else if (ratio > 1) {
  774. color = 'blue';
  775. }
  776. return (
  777. <Tag color={color}>
  778. {ratio}x {i18next.t('倍率')}
  779. </Tag>
  780. );
  781. }
  782. const measureTextWidth = (
  783. text,
  784. style = {
  785. fontSize: '14px',
  786. fontFamily:
  787. '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
  788. },
  789. containerWidth,
  790. ) => {
  791. const span = document.createElement('span');
  792. span.style.visibility = 'hidden';
  793. span.style.position = 'absolute';
  794. span.style.whiteSpace = 'nowrap';
  795. span.style.fontSize = style.fontSize;
  796. span.style.fontFamily = style.fontFamily;
  797. span.textContent = text;
  798. document.body.appendChild(span);
  799. const width = span.offsetWidth;
  800. document.body.removeChild(span);
  801. return width;
  802. };
  803. export function truncateText(text, maxWidth = 200) {
  804. const isMobileScreen = window.matchMedia(
  805. `(max-width: ${MOBILE_BREAKPOINT - 1}px)`,
  806. ).matches;
  807. if (!isMobileScreen) {
  808. return text;
  809. }
  810. if (!text) return text;
  811. try {
  812. // Handle percentage-based maxWidth
  813. let actualMaxWidth = maxWidth;
  814. if (typeof maxWidth === 'string' && maxWidth.endsWith('%')) {
  815. const percentage = parseFloat(maxWidth) / 100;
  816. // Use window width as fallback container width
  817. actualMaxWidth = window.innerWidth * percentage;
  818. }
  819. const width = measureTextWidth(text);
  820. if (width <= actualMaxWidth) return text;
  821. let left = 0;
  822. let right = text.length;
  823. let result = text;
  824. while (left <= right) {
  825. const mid = Math.floor((left + right) / 2);
  826. const truncated = text.slice(0, mid) + '...';
  827. const currentWidth = measureTextWidth(truncated);
  828. if (currentWidth <= actualMaxWidth) {
  829. result = truncated;
  830. left = mid + 1;
  831. } else {
  832. right = mid - 1;
  833. }
  834. }
  835. return result;
  836. } catch (error) {
  837. console.warn(
  838. 'Text measurement failed, falling back to character count',
  839. error,
  840. );
  841. if (text.length > 20) {
  842. return text.slice(0, 17) + '...';
  843. }
  844. return text;
  845. }
  846. }
  847. export const renderGroupOption = (item) => {
  848. const {
  849. disabled,
  850. selected,
  851. label,
  852. value,
  853. focused,
  854. className,
  855. style,
  856. onMouseEnter,
  857. onClick,
  858. empty,
  859. emptyContent,
  860. ...rest
  861. } = item;
  862. const baseStyle = {
  863. display: 'flex',
  864. justifyContent: 'space-between',
  865. alignItems: 'center',
  866. padding: '8px 16px',
  867. cursor: disabled ? 'not-allowed' : 'pointer',
  868. backgroundColor: focused ? 'var(--semi-color-fill-0)' : 'transparent',
  869. opacity: disabled ? 0.5 : 1,
  870. ...(selected && {
  871. backgroundColor: 'var(--semi-color-primary-light-default)',
  872. }),
  873. '&:hover': {
  874. backgroundColor: !disabled && 'var(--semi-color-fill-1)',
  875. },
  876. };
  877. const handleClick = () => {
  878. if (!disabled && onClick) {
  879. onClick();
  880. }
  881. };
  882. const handleMouseEnter = (e) => {
  883. if (!disabled && onMouseEnter) {
  884. onMouseEnter(e);
  885. }
  886. };
  887. return (
  888. <div
  889. style={baseStyle}
  890. onClick={handleClick}
  891. onMouseEnter={handleMouseEnter}
  892. >
  893. <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
  894. <Typography.Text strong type={disabled ? 'tertiary' : undefined}>
  895. {value}
  896. </Typography.Text>
  897. <Typography.Text type='secondary' size='small'>
  898. {label}
  899. </Typography.Text>
  900. </div>
  901. {item.ratio && renderRatio(item.ratio)}
  902. </div>
  903. );
  904. };
  905. export function renderNumber(num) {
  906. if (num >= 1000000000) {
  907. return (num / 1000000000).toFixed(1) + 'B';
  908. } else if (num >= 1000000) {
  909. return (num / 1000000).toFixed(1) + 'M';
  910. } else if (num >= 10000) {
  911. return (num / 1000).toFixed(1) + 'k';
  912. } else {
  913. return num;
  914. }
  915. }
  916. export function renderQuotaNumberWithDigit(num, digits = 2) {
  917. if (typeof num !== 'number' || isNaN(num)) {
  918. return 0;
  919. }
  920. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  921. num = num.toFixed(digits);
  922. if (quotaDisplayType === 'CNY') {
  923. return '¥' + num;
  924. } else if (quotaDisplayType === 'USD') {
  925. return '$' + num;
  926. } else if (quotaDisplayType === 'CUSTOM') {
  927. const statusStr = localStorage.getItem('status');
  928. let symbol = '¤';
  929. try {
  930. if (statusStr) {
  931. const s = JSON.parse(statusStr);
  932. symbol = s?.custom_currency_symbol || symbol;
  933. }
  934. } catch (e) {}
  935. return symbol + num;
  936. } else {
  937. return num;
  938. }
  939. }
  940. export function renderNumberWithPoint(num) {
  941. if (num === undefined) return '';
  942. num = num.toFixed(2);
  943. if (num >= 100000) {
  944. // Convert number to string to manipulate it
  945. let numStr = num.toString();
  946. // Find the position of the decimal point
  947. let decimalPointIndex = numStr.indexOf('.');
  948. let wholePart = numStr;
  949. let decimalPart = '';
  950. // If there is a decimal point, split the number into whole and decimal parts
  951. if (decimalPointIndex !== -1) {
  952. wholePart = numStr.slice(0, decimalPointIndex);
  953. decimalPart = numStr.slice(decimalPointIndex);
  954. }
  955. // Take the first two and last two digits of the whole number part
  956. let shortenedWholePart = wholePart.slice(0, 2) + '..' + wholePart.slice(-2);
  957. // Return the formatted number
  958. return shortenedWholePart + decimalPart;
  959. }
  960. // If the number is less than 100,000, return it unmodified
  961. return num;
  962. }
  963. export function getQuotaPerUnit() {
  964. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  965. quotaPerUnit = parseFloat(quotaPerUnit);
  966. return quotaPerUnit;
  967. }
  968. export function renderUnitWithQuota(quota) {
  969. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  970. quotaPerUnit = parseFloat(quotaPerUnit);
  971. quota = parseFloat(quota);
  972. return quotaPerUnit * quota;
  973. }
  974. export function getQuotaWithUnit(quota, digits = 6) {
  975. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  976. quotaPerUnit = parseFloat(quotaPerUnit);
  977. return (quota / quotaPerUnit).toFixed(digits);
  978. }
  979. export function renderQuotaWithAmount(amount) {
  980. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  981. if (quotaDisplayType === 'TOKENS') {
  982. return renderNumber(renderUnitWithQuota(amount));
  983. }
  984. if (quotaDisplayType === 'CNY') {
  985. return '¥' + amount;
  986. } else if (quotaDisplayType === 'CUSTOM') {
  987. const statusStr = localStorage.getItem('status');
  988. let symbol = '¤';
  989. try {
  990. if (statusStr) {
  991. const s = JSON.parse(statusStr);
  992. symbol = s?.custom_currency_symbol || symbol;
  993. }
  994. } catch (e) {}
  995. return symbol + amount;
  996. }
  997. return '$' + amount;
  998. }
  999. /**
  1000. * 获取当前货币配置信息
  1001. * @returns {Object} - { symbol, rate, type }
  1002. */
  1003. export function getCurrencyConfig() {
  1004. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  1005. const statusStr = localStorage.getItem('status');
  1006. let symbol = '$';
  1007. let rate = 1;
  1008. if (quotaDisplayType === 'CNY') {
  1009. symbol = '¥';
  1010. try {
  1011. if (statusStr) {
  1012. const s = JSON.parse(statusStr);
  1013. rate = s?.usd_exchange_rate || 7;
  1014. }
  1015. } catch (e) {}
  1016. } else if (quotaDisplayType === 'CUSTOM') {
  1017. try {
  1018. if (statusStr) {
  1019. const s = JSON.parse(statusStr);
  1020. symbol = s?.custom_currency_symbol || '¤';
  1021. rate = s?.custom_currency_exchange_rate || 1;
  1022. }
  1023. } catch (e) {}
  1024. }
  1025. return { symbol, rate, type: quotaDisplayType };
  1026. }
  1027. /**
  1028. * 将美元金额转换为当前选择的货币
  1029. * @param {number} usdAmount - 美元金额
  1030. * @param {number} digits - 小数位数
  1031. * @returns {string} - 格式化后的货币字符串
  1032. */
  1033. export function convertUSDToCurrency(usdAmount, digits = 2) {
  1034. const { symbol, rate } = getCurrencyConfig();
  1035. const convertedAmount = usdAmount * rate;
  1036. return symbol + convertedAmount.toFixed(digits);
  1037. }
  1038. export function renderQuota(quota, digits = 2) {
  1039. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  1040. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  1041. quotaPerUnit = parseFloat(quotaPerUnit);
  1042. if (quotaDisplayType === 'TOKENS') {
  1043. return renderNumber(quota);
  1044. }
  1045. const resultUSD = quota / quotaPerUnit;
  1046. let symbol = '$';
  1047. let value = resultUSD;
  1048. if (quotaDisplayType === 'CNY') {
  1049. const statusStr = localStorage.getItem('status');
  1050. let usdRate = 1;
  1051. try {
  1052. if (statusStr) {
  1053. const s = JSON.parse(statusStr);
  1054. usdRate = s?.usd_exchange_rate || 1;
  1055. }
  1056. } catch (e) {}
  1057. value = resultUSD * usdRate;
  1058. symbol = '¥';
  1059. } else if (quotaDisplayType === 'CUSTOM') {
  1060. const statusStr = localStorage.getItem('status');
  1061. let symbolCustom = '¤';
  1062. let rate = 1;
  1063. try {
  1064. if (statusStr) {
  1065. const s = JSON.parse(statusStr);
  1066. symbolCustom = s?.custom_currency_symbol || symbolCustom;
  1067. rate = s?.custom_currency_exchange_rate || rate;
  1068. }
  1069. } catch (e) {}
  1070. value = resultUSD * rate;
  1071. symbol = symbolCustom;
  1072. }
  1073. const fixedResult = value.toFixed(digits);
  1074. if (parseFloat(fixedResult) === 0 && quota > 0 && value > 0) {
  1075. const minValue = Math.pow(10, -digits);
  1076. return symbol + minValue.toFixed(digits);
  1077. }
  1078. return symbol + fixedResult;
  1079. }
  1080. function isValidGroupRatio(ratio) {
  1081. return Number.isFinite(ratio) && ratio !== -1;
  1082. }
  1083. /**
  1084. * Helper function to get effective ratio and label
  1085. * @param {number} groupRatio - The default group ratio
  1086. * @param {number} user_group_ratio - The user-specific group ratio
  1087. * @returns {Object} - Object containing { ratio, label, useUserGroupRatio }
  1088. */
  1089. function getEffectiveRatio(groupRatio, user_group_ratio) {
  1090. const useUserGroupRatio = isValidGroupRatio(user_group_ratio);
  1091. const ratioLabel = useUserGroupRatio
  1092. ? i18next.t('专属倍率')
  1093. : i18next.t('分组倍率');
  1094. const effectiveRatio = useUserGroupRatio ? user_group_ratio : groupRatio;
  1095. return {
  1096. ratio: effectiveRatio,
  1097. label: ratioLabel,
  1098. useUserGroupRatio: useUserGroupRatio,
  1099. };
  1100. }
  1101. // Shared core for simple price rendering (used by OpenAI-like and Claude-like variants)
  1102. function renderPriceSimpleCore({
  1103. modelRatio,
  1104. modelPrice = -1,
  1105. groupRatio,
  1106. user_group_ratio,
  1107. cacheTokens = 0,
  1108. cacheRatio = 1.0,
  1109. cacheCreationTokens = 0,
  1110. cacheCreationRatio = 1.0,
  1111. cacheCreationTokens5m = 0,
  1112. cacheCreationRatio5m = 1.0,
  1113. cacheCreationTokens1h = 0,
  1114. cacheCreationRatio1h = 1.0,
  1115. image = false,
  1116. imageRatio = 1.0,
  1117. isSystemPromptOverride = false,
  1118. }) {
  1119. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1120. groupRatio,
  1121. user_group_ratio,
  1122. );
  1123. const finalGroupRatio = effectiveGroupRatio;
  1124. const { symbol, rate } = getCurrencyConfig();
  1125. if (modelPrice !== -1) {
  1126. const displayPrice = (modelPrice * rate).toFixed(6);
  1127. return i18next.t('价格:{{symbol}}{{price}} * {{ratioType}}:{{ratio}}', {
  1128. symbol: symbol,
  1129. price: displayPrice,
  1130. ratioType: ratioLabel,
  1131. ratio: finalGroupRatio,
  1132. });
  1133. }
  1134. const hasSplitCacheCreation =
  1135. cacheCreationTokens5m > 0 || cacheCreationTokens1h > 0;
  1136. const shouldShowLegacyCacheCreation =
  1137. !hasSplitCacheCreation && cacheCreationTokens !== 0;
  1138. const shouldShowCache = cacheTokens !== 0;
  1139. const shouldShowCacheCreation5m =
  1140. hasSplitCacheCreation && cacheCreationTokens5m > 0;
  1141. const shouldShowCacheCreation1h =
  1142. hasSplitCacheCreation && cacheCreationTokens1h > 0;
  1143. const parts = [];
  1144. // base: model ratio
  1145. parts.push(i18next.t('模型: {{ratio}}'));
  1146. // cache part (label differs when with image)
  1147. if (shouldShowCache) {
  1148. parts.push(i18next.t('缓存: {{cacheRatio}}'));
  1149. }
  1150. if (hasSplitCacheCreation) {
  1151. if (shouldShowCacheCreation5m && shouldShowCacheCreation1h) {
  1152. parts.push(
  1153. i18next.t(
  1154. '缓存创建: 5m {{cacheCreationRatio5m}} / 1h {{cacheCreationRatio1h}}',
  1155. ),
  1156. );
  1157. } else if (shouldShowCacheCreation5m) {
  1158. parts.push(i18next.t('缓存创建: 5m {{cacheCreationRatio5m}}'));
  1159. } else if (shouldShowCacheCreation1h) {
  1160. parts.push(i18next.t('缓存创建: 1h {{cacheCreationRatio1h}}'));
  1161. }
  1162. } else if (shouldShowLegacyCacheCreation) {
  1163. parts.push(i18next.t('缓存创建: {{cacheCreationRatio}}'));
  1164. }
  1165. // image part
  1166. if (image) {
  1167. parts.push(i18next.t('图片输入: {{imageRatio}}'));
  1168. }
  1169. parts.push(`{{ratioType}}: {{groupRatio}}`);
  1170. let result = i18next.t(parts.join(' * '), {
  1171. ratio: modelRatio,
  1172. ratioType: ratioLabel,
  1173. groupRatio: finalGroupRatio,
  1174. cacheRatio: cacheRatio,
  1175. cacheCreationRatio: cacheCreationRatio,
  1176. cacheCreationRatio5m: cacheCreationRatio5m,
  1177. cacheCreationRatio1h: cacheCreationRatio1h,
  1178. imageRatio: imageRatio,
  1179. });
  1180. if (isSystemPromptOverride) {
  1181. result += '\n\r' + i18next.t('系统提示覆盖');
  1182. }
  1183. return result;
  1184. }
  1185. export function renderModelPrice(
  1186. inputTokens,
  1187. completionTokens,
  1188. modelRatio,
  1189. modelPrice = -1,
  1190. completionRatio,
  1191. groupRatio,
  1192. user_group_ratio,
  1193. cacheTokens = 0,
  1194. cacheRatio = 1.0,
  1195. image = false,
  1196. imageRatio = 1.0,
  1197. imageOutputTokens = 0,
  1198. webSearch = false,
  1199. webSearchCallCount = 0,
  1200. webSearchPrice = 0,
  1201. fileSearch = false,
  1202. fileSearchCallCount = 0,
  1203. fileSearchPrice = 0,
  1204. audioInputSeperatePrice = false,
  1205. audioInputTokens = 0,
  1206. audioInputPrice = 0,
  1207. imageGenerationCall = false,
  1208. imageGenerationCallPrice = 0,
  1209. userChannelRatio,
  1210. ) {
  1211. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1212. groupRatio,
  1213. user_group_ratio,
  1214. );
  1215. groupRatio = effectiveGroupRatio;
  1216. // 获取货币配置
  1217. const { symbol, rate } = getCurrencyConfig();
  1218. const ucr = (userChannelRatio != null && userChannelRatio !== 1.0) ? userChannelRatio : null;
  1219. if (modelPrice !== -1) {
  1220. const displayPrice = (modelPrice * rate).toFixed(6);
  1221. const displayTotal = (modelPrice * groupRatio * (ucr || 1) * rate).toFixed(6);
  1222. const ratioParts = `${ratioLabel}:${groupRatio}` + (ucr ? ` * 用户倍率:${ucr}` : '');
  1223. return i18next.t(
  1224. '模型价格:{{symbol}}{{price}} * {{ratioParts}} = {{symbol}}{{total}}',
  1225. {
  1226. symbol: symbol,
  1227. price: displayPrice,
  1228. ratioParts,
  1229. total: displayTotal,
  1230. },
  1231. );
  1232. } else {
  1233. if (completionRatio === undefined) {
  1234. completionRatio = 0;
  1235. }
  1236. let inputRatioPrice = modelRatio * 2.0;
  1237. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  1238. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  1239. let imageRatioPrice = modelRatio * 2.0 * imageRatio;
  1240. // Calculate effective input tokens (non-cached + cached with ratio applied)
  1241. let effectiveInputTokens =
  1242. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  1243. // Handle image tokens if present
  1244. if (image && imageOutputTokens > 0) {
  1245. effectiveInputTokens =
  1246. inputTokens - imageOutputTokens + imageOutputTokens * imageRatio;
  1247. }
  1248. if (audioInputTokens > 0) {
  1249. effectiveInputTokens -= audioInputTokens;
  1250. }
  1251. let price =
  1252. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1253. (audioInputTokens / 1000000) * audioInputPrice * groupRatio +
  1254. (completionTokens / 1000000) * completionRatioPrice * groupRatio +
  1255. (webSearchCallCount / 1000) * webSearchPrice * groupRatio +
  1256. (fileSearchCallCount / 1000) * fileSearchPrice * groupRatio +
  1257. imageGenerationCallPrice * groupRatio;
  1258. if (ucr) {
  1259. price *= ucr;
  1260. }
  1261. return (
  1262. <>
  1263. <article>
  1264. <p>
  1265. {i18next.t(
  1266. '输入价格:{{symbol}}{{price}} / 1M tokens{{audioPrice}}',
  1267. {
  1268. symbol: symbol,
  1269. price: (inputRatioPrice * rate).toFixed(6),
  1270. audioPrice: audioInputSeperatePrice
  1271. ? i18next.t(',音频 {{symbol}}{{price}} / 1M tokens', { symbol, price: (audioInputPrice * rate).toFixed(6) })
  1272. : '',
  1273. },
  1274. )}
  1275. </p>
  1276. <p>
  1277. {i18next.t(
  1278. '输出价格:{{symbol}}{{price}} * {{completionRatio}} = {{symbol}}{{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1279. {
  1280. symbol: symbol,
  1281. price: (inputRatioPrice * rate).toFixed(6),
  1282. total: (completionRatioPrice * rate).toFixed(6),
  1283. completionRatio: completionRatio,
  1284. },
  1285. )}
  1286. </p>
  1287. {cacheTokens > 0 && (
  1288. <p>
  1289. {i18next.t(
  1290. '缓存价格:{{symbol}}{{price}} * {{cacheRatio}} = {{symbol}}{{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1291. {
  1292. symbol: symbol,
  1293. price: (inputRatioPrice * rate).toFixed(6),
  1294. total: (inputRatioPrice * cacheRatio * rate).toFixed(6),
  1295. cacheRatio: cacheRatio,
  1296. },
  1297. )}
  1298. </p>
  1299. )}
  1300. {image && imageOutputTokens > 0 && (
  1301. <p>
  1302. {i18next.t(
  1303. '图片输入价格:{{symbol}}{{price}} * {{ratio}} = {{symbol}}{{total}} / 1M tokens (图片倍率: {{imageRatio}})',
  1304. {
  1305. symbol: symbol,
  1306. price: (imageRatioPrice * rate).toFixed(6),
  1307. ratio: groupRatio,
  1308. total: (imageRatioPrice * groupRatio * rate).toFixed(6),
  1309. imageRatio: imageRatio,
  1310. },
  1311. )}
  1312. </p>
  1313. )}
  1314. {webSearch && webSearchCallCount > 0 && (
  1315. <p>
  1316. {i18next.t('Web搜索价格:{{symbol}}{{price}} / 1K 次', {
  1317. symbol: symbol,
  1318. price: (webSearchPrice * rate).toFixed(6),
  1319. })}
  1320. </p>
  1321. )}
  1322. {fileSearch && fileSearchCallCount > 0 && (
  1323. <p>
  1324. {i18next.t('文件搜索价格:{{symbol}}{{price}} / 1K 次', {
  1325. symbol: symbol,
  1326. price: (fileSearchPrice * rate).toFixed(6),
  1327. })}
  1328. </p>
  1329. )}
  1330. {imageGenerationCall && imageGenerationCallPrice > 0 && (
  1331. <p>
  1332. {i18next.t('图片生成调用:{{symbol}}{{price}} / 1次', {
  1333. symbol: symbol,
  1334. price: (imageGenerationCallPrice * rate).toFixed(6),
  1335. })}
  1336. </p>
  1337. )}
  1338. <p>
  1339. {(() => {
  1340. // 构建输入部分描述
  1341. let inputDesc = '';
  1342. if (image && imageOutputTokens > 0) {
  1343. inputDesc = i18next.t(
  1344. '(输入 {{nonImageInput}} tokens + 图片输入 {{imageInput}} tokens * {{imageRatio}} / 1M tokens * {{symbol}}{{price}}',
  1345. {
  1346. nonImageInput: inputTokens - imageOutputTokens,
  1347. imageInput: imageOutputTokens,
  1348. imageRatio: imageRatio,
  1349. symbol: symbol,
  1350. price: (inputRatioPrice * rate).toFixed(6),
  1351. },
  1352. );
  1353. } else if (cacheTokens > 0) {
  1354. inputDesc = i18next.t(
  1355. '(输入 {{nonCacheInput}} tokens / 1M tokens * {{symbol}}{{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * {{symbol}}{{cachePrice}}',
  1356. {
  1357. nonCacheInput: inputTokens - cacheTokens,
  1358. cacheInput: cacheTokens,
  1359. symbol: symbol,
  1360. price: (inputRatioPrice * rate).toFixed(6),
  1361. cachePrice: (cacheRatioPrice * rate).toFixed(6),
  1362. },
  1363. );
  1364. } else if (audioInputSeperatePrice && audioInputTokens > 0) {
  1365. inputDesc = i18next.t(
  1366. '(输入 {{nonAudioInput}} tokens / 1M tokens * {{symbol}}{{price}} + 音频输入 {{audioInput}} tokens / 1M tokens * {{symbol}}{{audioPrice}}',
  1367. {
  1368. nonAudioInput: inputTokens - audioInputTokens,
  1369. audioInput: audioInputTokens,
  1370. symbol: symbol,
  1371. price: (inputRatioPrice * rate).toFixed(6),
  1372. audioPrice: (audioInputPrice * rate).toFixed(6),
  1373. },
  1374. );
  1375. } else {
  1376. inputDesc = i18next.t(
  1377. '(输入 {{input}} tokens / 1M tokens * {{symbol}}{{price}}',
  1378. {
  1379. input: inputTokens,
  1380. symbol: symbol,
  1381. price: (inputRatioPrice * rate).toFixed(6),
  1382. },
  1383. );
  1384. }
  1385. // 构建输出部分描述
  1386. const outputDesc = i18next.t(
  1387. '输出 {{completion}} tokens / 1M tokens * {{symbol}}{{compPrice}}) * {{ratioType}} {{ratio}}{{userRatio}}',
  1388. {
  1389. completion: completionTokens,
  1390. symbol: symbol,
  1391. compPrice: (completionRatioPrice * rate).toFixed(6),
  1392. ratio: groupRatio,
  1393. ratioType: ratioLabel,
  1394. userRatio: ucr ? ` * 用户倍率 ${ucr}` : '',
  1395. },
  1396. );
  1397. // 构建额外服务描述
  1398. const extraServices = [
  1399. webSearch && webSearchCallCount > 0
  1400. ? i18next.t(
  1401. ' + Web搜索 {{count}}次 / 1K 次 * {{symbol}}{{price}} * {{ratioType}} {{ratio}}',
  1402. {
  1403. count: webSearchCallCount,
  1404. symbol: symbol,
  1405. price: (webSearchPrice * rate).toFixed(6),
  1406. ratio: groupRatio,
  1407. ratioType: ratioLabel,
  1408. },
  1409. )
  1410. : '',
  1411. fileSearch && fileSearchCallCount > 0
  1412. ? i18next.t(
  1413. ' + 文件搜索 {{count}}次 / 1K 次 * {{symbol}}{{price}} * {{ratioType}} {{ratio}}',
  1414. {
  1415. count: fileSearchCallCount,
  1416. symbol: symbol,
  1417. price: (fileSearchPrice * rate).toFixed(6),
  1418. ratio: groupRatio,
  1419. ratioType: ratioLabel,
  1420. },
  1421. )
  1422. : '',
  1423. imageGenerationCall && imageGenerationCallPrice > 0
  1424. ? i18next.t(
  1425. ' + 图片生成调用 {{symbol}}{{price}} / 1次 * {{ratioType}} {{ratio}}',
  1426. {
  1427. symbol: symbol,
  1428. price: (imageGenerationCallPrice * rate).toFixed(6),
  1429. ratio: groupRatio,
  1430. ratioType: ratioLabel,
  1431. },
  1432. )
  1433. : '',
  1434. ].join('');
  1435. return i18next.t(
  1436. '{{inputDesc}} + {{outputDesc}}{{extraServices}} = {{symbol}}{{total}}',
  1437. {
  1438. inputDesc,
  1439. outputDesc,
  1440. extraServices,
  1441. symbol: symbol,
  1442. total: (price * rate).toFixed(6),
  1443. },
  1444. );
  1445. })()}
  1446. </p>
  1447. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1448. </article>
  1449. </>
  1450. );
  1451. }
  1452. }
  1453. export function renderLogContent(
  1454. modelRatio,
  1455. completionRatio,
  1456. modelPrice = -1,
  1457. groupRatio,
  1458. user_group_ratio,
  1459. cacheRatio = 1.0,
  1460. image = false,
  1461. imageRatio = 1.0,
  1462. webSearch = false,
  1463. webSearchCallCount = 0,
  1464. fileSearch = false,
  1465. fileSearchCallCount = 0,
  1466. userChannelRatio,
  1467. ) {
  1468. const {
  1469. ratio,
  1470. label: ratioLabel,
  1471. useUserGroupRatio: useUserGroupRatio,
  1472. } = getEffectiveRatio(groupRatio, user_group_ratio);
  1473. // 获取货币配置
  1474. const { symbol, rate } = getCurrencyConfig();
  1475. const userRatioSuffix = (userChannelRatio != null && userChannelRatio !== 1.0)
  1476. ? i18next.t(',用户倍率 {{userChannelRatio}}', { userChannelRatio })
  1477. : '';
  1478. let result;
  1479. if (modelPrice !== -1) {
  1480. result = i18next.t('模型价格 {{symbol}}{{price}},{{ratioType}} {{ratio}}', {
  1481. symbol: symbol,
  1482. price: (modelPrice * rate).toFixed(6),
  1483. ratioType: ratioLabel,
  1484. ratio,
  1485. });
  1486. } else if (image) {
  1487. result = i18next.t(
  1488. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},图片输入倍率 {{imageRatio}},{{ratioType}} {{ratio}}',
  1489. {
  1490. modelRatio: modelRatio,
  1491. cacheRatio: cacheRatio,
  1492. completionRatio: completionRatio,
  1493. imageRatio: imageRatio,
  1494. ratioType: ratioLabel,
  1495. ratio,
  1496. },
  1497. );
  1498. } else if (webSearch) {
  1499. result = i18next.t(
  1500. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}},Web 搜索调用 {{webSearchCallCount}} 次',
  1501. {
  1502. modelRatio: modelRatio,
  1503. cacheRatio: cacheRatio,
  1504. completionRatio: completionRatio,
  1505. ratioType: ratioLabel,
  1506. ratio,
  1507. webSearchCallCount,
  1508. },
  1509. );
  1510. } else {
  1511. result = i18next.t(
  1512. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}}',
  1513. {
  1514. modelRatio: modelRatio,
  1515. cacheRatio: cacheRatio,
  1516. completionRatio: completionRatio,
  1517. ratioType: ratioLabel,
  1518. ratio,
  1519. },
  1520. );
  1521. }
  1522. return result + userRatioSuffix;
  1523. }
  1524. export function renderModelPriceSimple(
  1525. modelRatio,
  1526. modelPrice = -1,
  1527. groupRatio,
  1528. user_group_ratio,
  1529. cacheTokens = 0,
  1530. cacheRatio = 1.0,
  1531. cacheCreationTokens = 0,
  1532. cacheCreationRatio = 1.0,
  1533. cacheCreationTokens5m = 0,
  1534. cacheCreationRatio5m = 1.0,
  1535. cacheCreationTokens1h = 0,
  1536. cacheCreationRatio1h = 1.0,
  1537. image = false,
  1538. imageRatio = 1.0,
  1539. isSystemPromptOverride = false,
  1540. provider = 'openai',
  1541. ) {
  1542. return renderPriceSimpleCore({
  1543. modelRatio,
  1544. modelPrice,
  1545. groupRatio,
  1546. user_group_ratio,
  1547. cacheTokens,
  1548. cacheRatio,
  1549. cacheCreationTokens,
  1550. cacheCreationRatio,
  1551. cacheCreationTokens5m,
  1552. cacheCreationRatio5m,
  1553. cacheCreationTokens1h,
  1554. cacheCreationRatio1h,
  1555. image,
  1556. imageRatio,
  1557. isSystemPromptOverride,
  1558. });
  1559. }
  1560. export function renderAudioModelPrice(
  1561. inputTokens,
  1562. completionTokens,
  1563. modelRatio,
  1564. modelPrice = -1,
  1565. completionRatio,
  1566. audioInputTokens,
  1567. audioCompletionTokens,
  1568. audioRatio,
  1569. audioCompletionRatio,
  1570. groupRatio,
  1571. user_group_ratio,
  1572. cacheTokens = 0,
  1573. cacheRatio = 1.0,
  1574. ) {
  1575. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1576. groupRatio,
  1577. user_group_ratio,
  1578. );
  1579. groupRatio = effectiveGroupRatio;
  1580. // 获取货币配置
  1581. const { symbol, rate } = getCurrencyConfig();
  1582. // 1 ratio = $0.002 / 1K tokens
  1583. if (modelPrice !== -1) {
  1584. return i18next.t(
  1585. '模型价格:{{symbol}}{{price}} * {{ratioType}}:{{ratio}} = {{symbol}}{{total}}',
  1586. {
  1587. symbol: symbol,
  1588. price: (modelPrice * rate).toFixed(6),
  1589. ratio: groupRatio,
  1590. total: (modelPrice * groupRatio * rate).toFixed(6),
  1591. ratioType: ratioLabel,
  1592. },
  1593. );
  1594. } else {
  1595. if (completionRatio === undefined) {
  1596. completionRatio = 0;
  1597. }
  1598. // try toFixed audioRatio
  1599. audioRatio = parseFloat(audioRatio).toFixed(6);
  1600. // 这里的 *2 是因为 1倍率=0.002刀,请勿删除
  1601. let inputRatioPrice = modelRatio * 2.0;
  1602. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  1603. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  1604. // Calculate effective input tokens (non-cached + cached with ratio applied)
  1605. const effectiveInputTokens =
  1606. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  1607. let textPrice =
  1608. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1609. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1610. let audioPrice =
  1611. (audioInputTokens / 1000000) * inputRatioPrice * audioRatio * groupRatio +
  1612. (audioCompletionTokens / 1000000) *
  1613. inputRatioPrice *
  1614. audioRatio *
  1615. audioCompletionRatio *
  1616. groupRatio;
  1617. let price = textPrice + audioPrice;
  1618. return (
  1619. <>
  1620. <article>
  1621. <p>
  1622. {i18next.t('提示价格:{{symbol}}{{price}} / 1M tokens', {
  1623. symbol: symbol,
  1624. price: (inputRatioPrice * rate).toFixed(6),
  1625. })}
  1626. </p>
  1627. <p>
  1628. {i18next.t(
  1629. '补全价格:{{symbol}}{{price}} * {{completionRatio}} = {{symbol}}{{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1630. {
  1631. symbol: symbol,
  1632. price: (inputRatioPrice * rate).toFixed(6),
  1633. total: (completionRatioPrice * rate).toFixed(6),
  1634. completionRatio: completionRatio,
  1635. },
  1636. )}
  1637. </p>
  1638. {cacheTokens > 0 && (
  1639. <p>
  1640. {i18next.t(
  1641. '缓存价格:{{symbol}}{{price}} * {{cacheRatio}} = {{symbol}}{{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1642. {
  1643. symbol: symbol,
  1644. price: (inputRatioPrice * rate).toFixed(6),
  1645. total: (inputRatioPrice * cacheRatio * rate).toFixed(6),
  1646. cacheRatio: cacheRatio,
  1647. },
  1648. )}
  1649. </p>
  1650. )}
  1651. <p>
  1652. {i18next.t(
  1653. '音频提示价格:{{symbol}}{{price}} * {{audioRatio}} = {{symbol}}{{total}} / 1M tokens (音频倍率: {{audioRatio}})',
  1654. {
  1655. symbol: symbol,
  1656. price: (inputRatioPrice * rate).toFixed(6),
  1657. total: (inputRatioPrice * audioRatio * rate).toFixed(6),
  1658. audioRatio: audioRatio,
  1659. },
  1660. )}
  1661. </p>
  1662. <p>
  1663. {i18next.t(
  1664. '音频补全价格:{{symbol}}{{price}} * {{audioRatio}} * {{audioCompRatio}} = {{symbol}}{{total}} / 1M tokens (音频补全倍率: {{audioCompRatio}})',
  1665. {
  1666. symbol: symbol,
  1667. price: (inputRatioPrice * rate).toFixed(6),
  1668. total: (
  1669. inputRatioPrice *
  1670. audioRatio *
  1671. audioCompletionRatio *
  1672. rate
  1673. ).toFixed(6),
  1674. audioRatio: audioRatio,
  1675. audioCompRatio: audioCompletionRatio,
  1676. },
  1677. )}
  1678. </p>
  1679. <p>
  1680. {cacheTokens > 0
  1681. ? i18next.t(
  1682. '文字提示 {{nonCacheInput}} tokens / 1M tokens * {{symbol}}{{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * {{symbol}}{{cachePrice}} + 文字补全 {{completion}} tokens / 1M tokens * {{symbol}}{{compPrice}} = {{symbol}}{{total}}',
  1683. {
  1684. nonCacheInput: inputTokens - cacheTokens,
  1685. cacheInput: cacheTokens,
  1686. symbol: symbol,
  1687. cachePrice: (inputRatioPrice * cacheRatio * rate).toFixed(
  1688. 6,
  1689. ),
  1690. price: (inputRatioPrice * rate).toFixed(6),
  1691. completion: completionTokens,
  1692. compPrice: (completionRatioPrice * rate).toFixed(6),
  1693. total: (textPrice * rate).toFixed(6),
  1694. },
  1695. )
  1696. : i18next.t(
  1697. '文字提示 {{input}} tokens / 1M tokens * {{symbol}}{{price}} + 文字补全 {{completion}} tokens / 1M tokens * {{symbol}}{{compPrice}} = {{symbol}}{{total}}',
  1698. {
  1699. input: inputTokens,
  1700. symbol: symbol,
  1701. price: (inputRatioPrice * rate).toFixed(6),
  1702. completion: completionTokens,
  1703. compPrice: (completionRatioPrice * rate).toFixed(6),
  1704. total: (textPrice * rate).toFixed(6),
  1705. },
  1706. )}
  1707. </p>
  1708. <p>
  1709. {i18next.t(
  1710. '音频提示 {{input}} tokens / 1M tokens * {{symbol}}{{audioInputPrice}} + 音频补全 {{completion}} tokens / 1M tokens * {{symbol}}{{audioCompPrice}} = {{symbol}}{{total}}',
  1711. {
  1712. input: audioInputTokens,
  1713. completion: audioCompletionTokens,
  1714. symbol: symbol,
  1715. audioInputPrice: (audioRatio * inputRatioPrice * rate).toFixed(
  1716. 6,
  1717. ),
  1718. audioCompPrice: (
  1719. audioRatio *
  1720. audioCompletionRatio *
  1721. inputRatioPrice *
  1722. rate
  1723. ).toFixed(6),
  1724. total: (audioPrice * rate).toFixed(6),
  1725. },
  1726. )}
  1727. </p>
  1728. <p>
  1729. {i18next.t(
  1730. '总价:文字价格 {{textPrice}} + 音频价格 {{audioPrice}} = {{symbol}}{{total}}',
  1731. {
  1732. symbol: symbol,
  1733. total: (price * rate).toFixed(6),
  1734. textPrice: (textPrice * rate).toFixed(6),
  1735. audioPrice: (audioPrice * rate).toFixed(6),
  1736. },
  1737. )}
  1738. </p>
  1739. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1740. </article>
  1741. </>
  1742. );
  1743. }
  1744. }
  1745. export function renderQuotaWithPrompt(quota, digits) {
  1746. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  1747. if (quotaDisplayType !== 'TOKENS') {
  1748. return i18next.t('等价金额:') + renderQuota(quota, digits);
  1749. }
  1750. return '';
  1751. }
  1752. export function renderClaudeModelPrice(
  1753. inputTokens,
  1754. completionTokens,
  1755. modelRatio,
  1756. modelPrice = -1,
  1757. completionRatio,
  1758. groupRatio,
  1759. user_group_ratio,
  1760. cacheTokens = 0,
  1761. cacheRatio = 1.0,
  1762. cacheCreationTokens = 0,
  1763. cacheCreationRatio = 1.0,
  1764. cacheCreationTokens5m = 0,
  1765. cacheCreationRatio5m = 1.0,
  1766. cacheCreationTokens1h = 0,
  1767. cacheCreationRatio1h = 1.0,
  1768. ) {
  1769. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1770. groupRatio,
  1771. user_group_ratio,
  1772. );
  1773. groupRatio = effectiveGroupRatio;
  1774. // 获取货币配置
  1775. const { symbol, rate } = getCurrencyConfig();
  1776. if (modelPrice !== -1) {
  1777. return i18next.t(
  1778. '模型价格:{{symbol}}{{price}} * {{ratioType}}:{{ratio}} = {{symbol}}{{total}}',
  1779. {
  1780. symbol: symbol,
  1781. price: (modelPrice * rate).toFixed(6),
  1782. ratioType: ratioLabel,
  1783. ratio: groupRatio,
  1784. total: (modelPrice * groupRatio * rate).toFixed(6),
  1785. },
  1786. );
  1787. } else {
  1788. if (completionRatio === undefined) {
  1789. completionRatio = 0;
  1790. }
  1791. const completionRatioValue = completionRatio || 0;
  1792. const inputRatioPrice = modelRatio * 2.0;
  1793. const completionRatioPrice = modelRatio * 2.0 * completionRatioValue;
  1794. const cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  1795. const cacheCreationRatioPrice = modelRatio * 2.0 * cacheCreationRatio;
  1796. const cacheCreationRatioPrice5m = modelRatio * 2.0 * cacheCreationRatio5m;
  1797. const cacheCreationRatioPrice1h = modelRatio * 2.0 * cacheCreationRatio1h;
  1798. const hasSplitCacheCreation =
  1799. cacheCreationTokens5m > 0 || cacheCreationTokens1h > 0;
  1800. const shouldShowCache = cacheTokens > 0;
  1801. const shouldShowLegacyCacheCreation =
  1802. !hasSplitCacheCreation && cacheCreationTokens > 0;
  1803. const shouldShowCacheCreation5m =
  1804. hasSplitCacheCreation && cacheCreationTokens5m > 0;
  1805. const shouldShowCacheCreation1h =
  1806. hasSplitCacheCreation && cacheCreationTokens1h > 0;
  1807. // Calculate effective input tokens (non-cached + cached with ratio applied + cache creation with ratio applied)
  1808. const nonCachedTokens = inputTokens;
  1809. const legacyCacheCreationTokens = hasSplitCacheCreation
  1810. ? 0
  1811. : cacheCreationTokens;
  1812. const effectiveInputTokens =
  1813. nonCachedTokens +
  1814. cacheTokens * cacheRatio +
  1815. legacyCacheCreationTokens * cacheCreationRatio +
  1816. cacheCreationTokens5m * cacheCreationRatio5m +
  1817. cacheCreationTokens1h * cacheCreationRatio1h;
  1818. let price =
  1819. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1820. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1821. const inputUnitPrice = inputRatioPrice * rate;
  1822. const completionUnitPrice = completionRatioPrice * rate;
  1823. const cacheUnitPrice = cacheRatioPrice * rate;
  1824. const cacheCreationUnitPrice = cacheCreationRatioPrice * rate;
  1825. const cacheCreationUnitPrice5m = cacheCreationRatioPrice5m * rate;
  1826. const cacheCreationUnitPrice1h = cacheCreationRatioPrice1h * rate;
  1827. const cacheCreationUnitPriceTotal =
  1828. cacheCreationUnitPrice5m + cacheCreationUnitPrice1h;
  1829. const breakdownSegments = [
  1830. i18next.t('提示 {{input}} tokens / 1M tokens * {{symbol}}{{price}}', {
  1831. input: inputTokens,
  1832. symbol,
  1833. price: inputUnitPrice.toFixed(6),
  1834. }),
  1835. ];
  1836. if (shouldShowCache) {
  1837. breakdownSegments.push(
  1838. i18next.t(
  1839. '缓存 {{tokens}} tokens / 1M tokens * {{symbol}}{{price}} (倍率: {{ratio}})',
  1840. {
  1841. tokens: cacheTokens,
  1842. symbol,
  1843. price: cacheUnitPrice.toFixed(6),
  1844. ratio: cacheRatio,
  1845. },
  1846. ),
  1847. );
  1848. }
  1849. if (shouldShowLegacyCacheCreation) {
  1850. breakdownSegments.push(
  1851. i18next.t(
  1852. '缓存创建 {{tokens}} tokens / 1M tokens * {{symbol}}{{price}} (倍率: {{ratio}})',
  1853. {
  1854. tokens: cacheCreationTokens,
  1855. symbol,
  1856. price: cacheCreationUnitPrice.toFixed(6),
  1857. ratio: cacheCreationRatio,
  1858. },
  1859. ),
  1860. );
  1861. }
  1862. if (shouldShowCacheCreation5m) {
  1863. breakdownSegments.push(
  1864. i18next.t(
  1865. '5m缓存创建 {{tokens}} tokens / 1M tokens * {{symbol}}{{price}} (倍率: {{ratio}})',
  1866. {
  1867. tokens: cacheCreationTokens5m,
  1868. symbol,
  1869. price: cacheCreationUnitPrice5m.toFixed(6),
  1870. ratio: cacheCreationRatio5m,
  1871. },
  1872. ),
  1873. );
  1874. }
  1875. if (shouldShowCacheCreation1h) {
  1876. breakdownSegments.push(
  1877. i18next.t(
  1878. '1h缓存创建 {{tokens}} tokens / 1M tokens * {{symbol}}{{price}} (倍率: {{ratio}})',
  1879. {
  1880. tokens: cacheCreationTokens1h,
  1881. symbol,
  1882. price: cacheCreationUnitPrice1h.toFixed(6),
  1883. ratio: cacheCreationRatio1h,
  1884. },
  1885. ),
  1886. );
  1887. }
  1888. breakdownSegments.push(
  1889. i18next.t(
  1890. '补全 {{completion}} tokens / 1M tokens * {{symbol}}{{price}}',
  1891. {
  1892. completion: completionTokens,
  1893. symbol,
  1894. price: completionUnitPrice.toFixed(6),
  1895. },
  1896. ),
  1897. );
  1898. const breakdownText = breakdownSegments.join(' + ');
  1899. return (
  1900. <>
  1901. <article>
  1902. <p>
  1903. {i18next.t('提示价格:{{symbol}}{{price}} / 1M tokens', {
  1904. symbol: symbol,
  1905. price: (inputRatioPrice * rate).toFixed(6),
  1906. })}
  1907. </p>
  1908. <p>
  1909. {i18next.t(
  1910. '补全价格:{{symbol}}{{price}} * {{ratio}} = {{symbol}}{{total}} / 1M tokens',
  1911. {
  1912. symbol: symbol,
  1913. price: (inputRatioPrice * rate).toFixed(6),
  1914. ratio: completionRatio,
  1915. total: (completionRatioPrice * rate).toFixed(6),
  1916. },
  1917. )}
  1918. </p>
  1919. {shouldShowCache && (
  1920. <p>
  1921. {i18next.t(
  1922. '缓存价格:{{symbol}}{{price}} * {{ratio}} = {{symbol}}{{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1923. {
  1924. symbol: symbol,
  1925. price: (inputRatioPrice * rate).toFixed(6),
  1926. ratio: cacheRatio,
  1927. total: cacheUnitPrice.toFixed(6),
  1928. cacheRatio: cacheRatio,
  1929. },
  1930. )}
  1931. </p>
  1932. )}
  1933. {shouldShowLegacyCacheCreation && (
  1934. <p>
  1935. {i18next.t(
  1936. '缓存创建价格:{{symbol}}{{price}} * {{ratio}} = {{symbol}}{{total}} / 1M tokens (缓存创建倍率: {{cacheCreationRatio}})',
  1937. {
  1938. symbol: symbol,
  1939. price: (inputRatioPrice * rate).toFixed(6),
  1940. ratio: cacheCreationRatio,
  1941. total: cacheCreationUnitPrice.toFixed(6),
  1942. cacheCreationRatio: cacheCreationRatio,
  1943. },
  1944. )}
  1945. </p>
  1946. )}
  1947. {shouldShowCacheCreation5m && (
  1948. <p>
  1949. {i18next.t(
  1950. '5m缓存创建价格:{{symbol}}{{price}} * {{ratio}} = {{symbol}}{{total}} / 1M tokens (5m缓存创建倍率: {{cacheCreationRatio5m}})',
  1951. {
  1952. symbol: symbol,
  1953. price: (inputRatioPrice * rate).toFixed(6),
  1954. ratio: cacheCreationRatio5m,
  1955. total: cacheCreationUnitPrice5m.toFixed(6),
  1956. cacheCreationRatio5m: cacheCreationRatio5m,
  1957. },
  1958. )}
  1959. </p>
  1960. )}
  1961. {shouldShowCacheCreation1h && (
  1962. <p>
  1963. {i18next.t(
  1964. '1h缓存创建价格:{{symbol}}{{price}} * {{ratio}} = {{symbol}}{{total}} / 1M tokens (1h缓存创建倍率: {{cacheCreationRatio1h}})',
  1965. {
  1966. symbol: symbol,
  1967. price: (inputRatioPrice * rate).toFixed(6),
  1968. ratio: cacheCreationRatio1h,
  1969. total: cacheCreationUnitPrice1h.toFixed(6),
  1970. cacheCreationRatio1h: cacheCreationRatio1h,
  1971. },
  1972. )}
  1973. </p>
  1974. )}
  1975. {shouldShowCacheCreation5m && shouldShowCacheCreation1h && (
  1976. <p>
  1977. {i18next.t(
  1978. '缓存创建价格合计:5m {{symbol}}{{five}} + 1h {{symbol}}{{one}} = {{symbol}}{{total}} / 1M tokens',
  1979. {
  1980. symbol: symbol,
  1981. five: cacheCreationUnitPrice5m.toFixed(6),
  1982. one: cacheCreationUnitPrice1h.toFixed(6),
  1983. total: cacheCreationUnitPriceTotal.toFixed(6),
  1984. },
  1985. )}
  1986. </p>
  1987. )}
  1988. <p></p>
  1989. <p>
  1990. {i18next.t(
  1991. '{{breakdown}} * {{ratioType}} {{ratio}} = {{symbol}}{{total}}',
  1992. {
  1993. breakdown: breakdownText,
  1994. ratioType: ratioLabel,
  1995. ratio: groupRatio,
  1996. symbol: symbol,
  1997. total: (price * rate).toFixed(6),
  1998. },
  1999. )}
  2000. </p>
  2001. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  2002. </article>
  2003. </>
  2004. );
  2005. }
  2006. }
  2007. export function renderClaudeLogContent(
  2008. modelRatio,
  2009. completionRatio,
  2010. modelPrice = -1,
  2011. groupRatio,
  2012. user_group_ratio,
  2013. cacheRatio = 1.0,
  2014. cacheCreationRatio = 1.0,
  2015. cacheCreationTokens5m = 0,
  2016. cacheCreationRatio5m = 1.0,
  2017. cacheCreationTokens1h = 0,
  2018. cacheCreationRatio1h = 1.0,
  2019. userChannelRatio,
  2020. ) {
  2021. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  2022. groupRatio,
  2023. user_group_ratio,
  2024. );
  2025. groupRatio = effectiveGroupRatio;
  2026. // 获取货币配置
  2027. const { symbol, rate } = getCurrencyConfig();
  2028. const userRatioSuffix = (userChannelRatio != null && userChannelRatio !== 1.0)
  2029. ? i18next.t(',用户倍率 {{userChannelRatio}}', { userChannelRatio })
  2030. : '';
  2031. if (modelPrice !== -1) {
  2032. return i18next.t('模型价格 {{symbol}}{{price}},{{ratioType}} {{ratio}}', {
  2033. symbol: symbol,
  2034. price: (modelPrice * rate).toFixed(6),
  2035. ratioType: ratioLabel,
  2036. ratio: groupRatio,
  2037. }) + userRatioSuffix;
  2038. } else {
  2039. const hasSplitCacheCreation =
  2040. cacheCreationTokens5m > 0 || cacheCreationTokens1h > 0;
  2041. const shouldShowCacheCreation5m =
  2042. hasSplitCacheCreation && cacheCreationTokens5m > 0;
  2043. const shouldShowCacheCreation1h =
  2044. hasSplitCacheCreation && cacheCreationTokens1h > 0;
  2045. let cacheCreationPart = null;
  2046. if (hasSplitCacheCreation) {
  2047. if (shouldShowCacheCreation5m && shouldShowCacheCreation1h) {
  2048. cacheCreationPart = i18next.t(
  2049. '缓存创建倍率 5m {{cacheCreationRatio5m}} / 1h {{cacheCreationRatio1h}}',
  2050. {
  2051. cacheCreationRatio5m,
  2052. cacheCreationRatio1h,
  2053. },
  2054. );
  2055. } else if (shouldShowCacheCreation5m) {
  2056. cacheCreationPart = i18next.t(
  2057. '缓存创建倍率 5m {{cacheCreationRatio5m}}',
  2058. {
  2059. cacheCreationRatio5m,
  2060. },
  2061. );
  2062. } else if (shouldShowCacheCreation1h) {
  2063. cacheCreationPart = i18next.t(
  2064. '缓存创建倍率 1h {{cacheCreationRatio1h}}',
  2065. {
  2066. cacheCreationRatio1h,
  2067. },
  2068. );
  2069. }
  2070. }
  2071. if (!cacheCreationPart) {
  2072. cacheCreationPart = i18next.t('缓存创建倍率 {{cacheCreationRatio}}', {
  2073. cacheCreationRatio,
  2074. });
  2075. }
  2076. const parts = [
  2077. i18next.t('模型倍率 {{modelRatio}}', { modelRatio }),
  2078. i18next.t('输出倍率 {{completionRatio}}', { completionRatio }),
  2079. i18next.t('缓存倍率 {{cacheRatio}}', { cacheRatio }),
  2080. cacheCreationPart,
  2081. i18next.t('{{ratioType}} {{ratio}}', {
  2082. ratioType: ratioLabel,
  2083. ratio: groupRatio,
  2084. }),
  2085. ];
  2086. return parts.join(',') + userRatioSuffix;
  2087. }
  2088. }
  2089. // 已统一至 renderModelPriceSimple,若仍有遗留引用,请改为传入 provider='claude'
  2090. /**
  2091. * rehype 插件:将段落等文本节点拆分为逐词 <span>,并添加淡入动画 class。
  2092. * 仅在流式渲染阶段使用,避免已渲染文字重复动画。
  2093. */
  2094. export function rehypeSplitWordsIntoSpans(options = {}) {
  2095. const { previousContentLength = 0 } = options;
  2096. return (tree) => {
  2097. let currentCharCount = 0; // 当前已处理的字符数
  2098. visit(tree, 'element', (node) => {
  2099. if (
  2100. ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'strong'].includes(
  2101. node.tagName,
  2102. ) &&
  2103. node.children
  2104. ) {
  2105. const newChildren = [];
  2106. node.children.forEach((child) => {
  2107. if (child.type === 'text') {
  2108. try {
  2109. // 使用 Intl.Segmenter 精准拆分中英文及标点
  2110. const segmenter = new Intl.Segmenter('zh', {
  2111. granularity: 'word',
  2112. });
  2113. const segments = segmenter.segment(child.value);
  2114. Array.from(segments)
  2115. .map((seg) => seg.segment)
  2116. .filter(Boolean)
  2117. .forEach((word) => {
  2118. const wordStartPos = currentCharCount;
  2119. const wordEndPos = currentCharCount + word.length;
  2120. // 判断这个词是否是新增的(在 previousContentLength 之后)
  2121. const isNewContent = wordStartPos >= previousContentLength;
  2122. newChildren.push({
  2123. type: 'element',
  2124. tagName: 'span',
  2125. properties: {
  2126. className: isNewContent ? ['animate-fade-in'] : [],
  2127. },
  2128. children: [{ type: 'text', value: word }],
  2129. });
  2130. currentCharCount = wordEndPos;
  2131. });
  2132. } catch (_) {
  2133. // Fallback:如果浏览器不支持 Segmenter
  2134. const textStartPos = currentCharCount;
  2135. const isNewContent = textStartPos >= previousContentLength;
  2136. if (isNewContent) {
  2137. // 新内容,添加动画
  2138. newChildren.push({
  2139. type: 'element',
  2140. tagName: 'span',
  2141. properties: {
  2142. className: ['animate-fade-in'],
  2143. },
  2144. children: [{ type: 'text', value: child.value }],
  2145. });
  2146. } else {
  2147. // 旧内容,不添加动画
  2148. newChildren.push(child);
  2149. }
  2150. currentCharCount += child.value.length;
  2151. }
  2152. } else {
  2153. newChildren.push(child);
  2154. }
  2155. });
  2156. node.children = newChildren;
  2157. }
  2158. });
  2159. };
  2160. }