render.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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 [email protected]
  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.js';
  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. } from '@lobehub/icons';
  53. import {
  54. LayoutDashboard,
  55. TerminalSquare,
  56. MessageSquare,
  57. Key,
  58. BarChart3,
  59. Image as ImageIcon,
  60. CheckSquare,
  61. CreditCard,
  62. Layers,
  63. Gift,
  64. User,
  65. Settings,
  66. CircleUser,
  67. Package,
  68. } from 'lucide-react';
  69. // 获取侧边栏Lucide图标组件
  70. export function getLucideIcon(key, selected = false) {
  71. const size = 16;
  72. const strokeWidth = 2;
  73. const SELECTED_COLOR = 'var(--semi-color-primary)';
  74. const iconColor = selected ? SELECTED_COLOR : 'currentColor';
  75. const commonProps = {
  76. size,
  77. strokeWidth,
  78. className: `transition-colors duration-200 ${selected ? 'transition-transform duration-200 scale-105' : ''}`,
  79. };
  80. // 根据不同的key返回不同的图标
  81. switch (key) {
  82. case 'detail':
  83. return (
  84. <LayoutDashboard
  85. {...commonProps}
  86. color={iconColor}
  87. />
  88. );
  89. case 'playground':
  90. return (
  91. <TerminalSquare
  92. {...commonProps}
  93. color={iconColor}
  94. />
  95. );
  96. case 'chat':
  97. return (
  98. <MessageSquare
  99. {...commonProps}
  100. color={iconColor}
  101. />
  102. );
  103. case 'token':
  104. return (
  105. <Key
  106. {...commonProps}
  107. color={iconColor}
  108. />
  109. );
  110. case 'log':
  111. return (
  112. <BarChart3
  113. {...commonProps}
  114. color={iconColor}
  115. />
  116. );
  117. case 'midjourney':
  118. return (
  119. <ImageIcon
  120. {...commonProps}
  121. color={iconColor}
  122. />
  123. );
  124. case 'task':
  125. return (
  126. <CheckSquare
  127. {...commonProps}
  128. color={iconColor}
  129. />
  130. );
  131. case 'topup':
  132. return (
  133. <CreditCard
  134. {...commonProps}
  135. color={iconColor}
  136. />
  137. );
  138. case 'channel':
  139. return (
  140. <Layers
  141. {...commonProps}
  142. color={iconColor}
  143. />
  144. );
  145. case 'redemption':
  146. return (
  147. <Gift
  148. {...commonProps}
  149. color={iconColor}
  150. />
  151. );
  152. case 'user':
  153. case 'personal':
  154. return (
  155. <User
  156. {...commonProps}
  157. color={iconColor}
  158. />
  159. );
  160. case 'models':
  161. return (
  162. <Package
  163. {...commonProps}
  164. color={iconColor}
  165. />
  166. );
  167. case 'setting':
  168. return (
  169. <Settings
  170. {...commonProps}
  171. color={iconColor}
  172. />
  173. );
  174. default:
  175. return (
  176. <CircleUser
  177. {...commonProps}
  178. color={iconColor}
  179. />
  180. );
  181. }
  182. }
  183. // 获取模型分类
  184. export const getModelCategories = (() => {
  185. let categoriesCache = null;
  186. let lastLocale = null;
  187. return (t) => {
  188. const currentLocale = i18next.language;
  189. if (categoriesCache && lastLocale === currentLocale) {
  190. return categoriesCache;
  191. }
  192. categoriesCache = {
  193. all: {
  194. label: t('全部模型'),
  195. icon: null,
  196. filter: () => true,
  197. },
  198. openai: {
  199. label: 'OpenAI',
  200. icon: <OpenAI />,
  201. filter: (model) =>
  202. model.model_name.toLowerCase().includes('gpt') ||
  203. model.model_name.toLowerCase().includes('dall-e') ||
  204. model.model_name.toLowerCase().includes('whisper') ||
  205. model.model_name.toLowerCase().includes('tts') ||
  206. model.model_name.toLowerCase().includes('text-') ||
  207. model.model_name.toLowerCase().includes('babbage') ||
  208. model.model_name.toLowerCase().includes('davinci') ||
  209. model.model_name.toLowerCase().includes('curie') ||
  210. model.model_name.toLowerCase().includes('ada') ||
  211. model.model_name.toLowerCase().includes('o1') ||
  212. model.model_name.toLowerCase().includes('o3') ||
  213. model.model_name.toLowerCase().includes('o4'),
  214. },
  215. anthropic: {
  216. label: 'Anthropic',
  217. icon: <Claude.Color />,
  218. filter: (model) => model.model_name.toLowerCase().includes('claude'),
  219. },
  220. gemini: {
  221. label: 'Gemini',
  222. icon: <Gemini.Color />,
  223. filter: (model) => model.model_name.toLowerCase().includes('gemini'),
  224. },
  225. moonshot: {
  226. label: 'Moonshot',
  227. icon: <Moonshot />,
  228. filter: (model) => model.model_name.toLowerCase().includes('moonshot'),
  229. },
  230. zhipu: {
  231. label: t('智谱'),
  232. icon: <Zhipu.Color />,
  233. filter: (model) =>
  234. model.model_name.toLowerCase().includes('chatglm') ||
  235. model.model_name.toLowerCase().includes('glm-'),
  236. },
  237. qwen: {
  238. label: t('通义千问'),
  239. icon: <Qwen.Color />,
  240. filter: (model) => model.model_name.toLowerCase().includes('qwen'),
  241. },
  242. deepseek: {
  243. label: 'DeepSeek',
  244. icon: <DeepSeek.Color />,
  245. filter: (model) => model.model_name.toLowerCase().includes('deepseek'),
  246. },
  247. minimax: {
  248. label: 'MiniMax',
  249. icon: <Minimax.Color />,
  250. filter: (model) => model.model_name.toLowerCase().includes('abab'),
  251. },
  252. baidu: {
  253. label: t('文心一言'),
  254. icon: <Wenxin.Color />,
  255. filter: (model) => model.model_name.toLowerCase().includes('ernie'),
  256. },
  257. xunfei: {
  258. label: t('讯飞星火'),
  259. icon: <Spark.Color />,
  260. filter: (model) => model.model_name.toLowerCase().includes('spark'),
  261. },
  262. midjourney: {
  263. label: 'Midjourney',
  264. icon: <Midjourney />,
  265. filter: (model) => model.model_name.toLowerCase().includes('mj_'),
  266. },
  267. tencent: {
  268. label: t('腾讯混元'),
  269. icon: <Hunyuan.Color />,
  270. filter: (model) => model.model_name.toLowerCase().includes('hunyuan'),
  271. },
  272. cohere: {
  273. label: 'Cohere',
  274. icon: <Cohere.Color />,
  275. filter: (model) => model.model_name.toLowerCase().includes('command'),
  276. },
  277. cloudflare: {
  278. label: 'Cloudflare',
  279. icon: <Cloudflare.Color />,
  280. filter: (model) => model.model_name.toLowerCase().includes('@cf/'),
  281. },
  282. ai360: {
  283. label: t('360智脑'),
  284. icon: <Ai360.Color />,
  285. filter: (model) => model.model_name.toLowerCase().includes('360'),
  286. },
  287. yi: {
  288. label: t('零一万物'),
  289. icon: <Yi.Color />,
  290. filter: (model) => model.model_name.toLowerCase().includes('yi'),
  291. },
  292. jina: {
  293. label: 'Jina',
  294. icon: <Jina />,
  295. filter: (model) => model.model_name.toLowerCase().includes('jina'),
  296. },
  297. mistral: {
  298. label: 'Mistral AI',
  299. icon: <Mistral.Color />,
  300. filter: (model) => model.model_name.toLowerCase().includes('mistral'),
  301. },
  302. xai: {
  303. label: 'xAI',
  304. icon: <XAI />,
  305. filter: (model) => model.model_name.toLowerCase().includes('grok'),
  306. },
  307. llama: {
  308. label: 'Llama',
  309. icon: <Ollama />,
  310. filter: (model) => model.model_name.toLowerCase().includes('llama'),
  311. },
  312. doubao: {
  313. label: t('豆包'),
  314. icon: <Doubao.Color />,
  315. filter: (model) => model.model_name.toLowerCase().includes('doubao'),
  316. },
  317. };
  318. lastLocale = currentLocale;
  319. return categoriesCache;
  320. };
  321. })();
  322. /**
  323. * 根据渠道类型返回对应的厂商图标
  324. * @param {number} channelType - 渠道类型值
  325. * @returns {JSX.Element|null} - 对应的厂商图标组件
  326. */
  327. export function getChannelIcon(channelType) {
  328. const iconSize = 14;
  329. switch (channelType) {
  330. case 1: // OpenAI
  331. case 3: // Azure OpenAI
  332. return <OpenAI size={iconSize} />;
  333. case 2: // Midjourney Proxy
  334. case 5: // Midjourney Proxy Plus
  335. return <Midjourney size={iconSize} />;
  336. case 36: // Suno API
  337. return <Suno size={iconSize} />;
  338. case 4: // Ollama
  339. return <Ollama size={iconSize} />;
  340. case 14: // Anthropic Claude
  341. case 33: // AWS Claude
  342. return <Claude.Color size={iconSize} />;
  343. case 41: // Vertex AI
  344. return <Gemini.Color size={iconSize} />;
  345. case 34: // Cohere
  346. return <Cohere.Color size={iconSize} />;
  347. case 39: // Cloudflare
  348. return <Cloudflare.Color size={iconSize} />;
  349. case 43: // DeepSeek
  350. return <DeepSeek.Color size={iconSize} />;
  351. case 15: // 百度文心千帆
  352. case 46: // 百度文心千帆V2
  353. return <Wenxin.Color size={iconSize} />;
  354. case 17: // 阿里通义千问
  355. return <Qwen.Color size={iconSize} />;
  356. case 18: // 讯飞星火认知
  357. return <Spark.Color size={iconSize} />;
  358. case 16: // 智谱 ChatGLM
  359. case 26: // 智谱 GLM-4V
  360. return <Zhipu.Color size={iconSize} />;
  361. case 24: // Google Gemini
  362. case 11: // Google PaLM2
  363. return <Gemini.Color size={iconSize} />;
  364. case 47: // Xinference
  365. return <Xinference.Color size={iconSize} />;
  366. case 25: // Moonshot
  367. return <Moonshot size={iconSize} />;
  368. case 20: // OpenRouter
  369. return <OpenRouter size={iconSize} />;
  370. case 19: // 360 智脑
  371. return <Ai360.Color size={iconSize} />;
  372. case 23: // 腾讯混元
  373. return <Hunyuan.Color size={iconSize} />;
  374. case 31: // 零一万物
  375. return <Yi.Color size={iconSize} />;
  376. case 35: // MiniMax
  377. return <Minimax.Color size={iconSize} />;
  378. case 37: // Dify
  379. return <Dify.Color size={iconSize} />;
  380. case 38: // Jina
  381. return <Jina size={iconSize} />;
  382. case 40: // SiliconCloud
  383. return <SiliconCloud.Color size={iconSize} />;
  384. case 42: // Mistral AI
  385. return <Mistral.Color size={iconSize} />;
  386. case 45: // 字节火山方舟、豆包通用
  387. return <Doubao.Color size={iconSize} />;
  388. case 48: // xAI
  389. return <XAI size={iconSize} />;
  390. case 49: // Coze
  391. return <Coze size={iconSize} />;
  392. case 50: // 可灵 Kling
  393. return <Kling.Color size={iconSize} />;
  394. case 51: // 即梦 Jimeng
  395. return <Jimeng.Color size={iconSize} />;
  396. case 8: // 自定义渠道
  397. case 22: // 知识库:FastGPT
  398. return <FastGPT.Color size={iconSize} />;
  399. case 21: // 知识库:AI Proxy
  400. case 44: // 嵌入模型:MokaAI M3E
  401. default:
  402. return null; // 未知类型或自定义渠道不显示图标
  403. }
  404. }
  405. /**
  406. * 根据图标名称动态获取 LobeHub 图标组件
  407. * @param {string} iconName - 图标名称
  408. * @param {number} size - 图标大小,默认为 14
  409. * @returns {JSX.Element} - 对应的图标组件或 Avatar
  410. */
  411. export function getLobeHubIcon(iconName, size = 14) {
  412. if (typeof iconName === 'string') iconName = iconName.trim();
  413. // 如果没有图标名称,返回 Avatar
  414. if (!iconName) {
  415. return <Avatar size="extra-extra-small">?</Avatar>;
  416. }
  417. let IconComponent;
  418. if (iconName.includes('.')) {
  419. const [base, variant] = iconName.split('.');
  420. const BaseIcon = LobeIcons[base];
  421. IconComponent = BaseIcon ? BaseIcon[variant] : undefined;
  422. } else {
  423. IconComponent = LobeIcons[iconName];
  424. }
  425. if (IconComponent && (typeof IconComponent === 'function' || typeof IconComponent === 'object')) {
  426. return <IconComponent size={size} />;
  427. }
  428. const firstLetter = iconName.charAt(0).toUpperCase();
  429. return <Avatar size="extra-extra-small">{firstLetter}</Avatar>;
  430. }
  431. // 颜色列表
  432. const colors = [
  433. 'amber',
  434. 'blue',
  435. 'cyan',
  436. 'green',
  437. 'grey',
  438. 'indigo',
  439. 'light-blue',
  440. 'lime',
  441. 'orange',
  442. 'pink',
  443. 'purple',
  444. 'red',
  445. 'teal',
  446. 'violet',
  447. 'yellow',
  448. ];
  449. // 基础10色色板 (N ≤ 10)
  450. const baseColors = [
  451. '#1664FF', // 主色
  452. '#1AC6FF',
  453. '#FF8A00',
  454. '#3CC780',
  455. '#7442D4',
  456. '#FFC400',
  457. '#304D77',
  458. '#B48DEB',
  459. '#009488',
  460. '#FF7DDA',
  461. ];
  462. // 扩展20色色板 (10 < N ≤ 20)
  463. const extendedColors = [
  464. '#1664FF',
  465. '#B2CFFF',
  466. '#1AC6FF',
  467. '#94EFFF',
  468. '#FF8A00',
  469. '#FFCE7A',
  470. '#3CC780',
  471. '#B9EDCD',
  472. '#7442D4',
  473. '#DDC5FA',
  474. '#FFC400',
  475. '#FAE878',
  476. '#304D77',
  477. '#8B959E',
  478. '#B48DEB',
  479. '#EFE3FF',
  480. '#009488',
  481. '#59BAA8',
  482. '#FF7DDA',
  483. '#FFCFEE',
  484. ];
  485. // 模型颜色映射
  486. export const modelColorMap = {
  487. 'dall-e': 'rgb(147,112,219)', // 深紫色
  488. // 'dall-e-2': 'rgb(147,112,219)', // 介于紫色和蓝色之间的色调
  489. 'dall-e-3': 'rgb(153,50,204)', // 介于紫罗兰和洋红之间的色调
  490. 'gpt-3.5-turbo': 'rgb(184,227,167)', // 浅绿色
  491. // 'gpt-3.5-turbo-0301': 'rgb(131,220,131)', // 亮绿色
  492. 'gpt-3.5-turbo-0613': 'rgb(60,179,113)', // 海洋绿
  493. 'gpt-3.5-turbo-1106': 'rgb(32,178,170)', // 浅海洋绿
  494. 'gpt-3.5-turbo-16k': 'rgb(149,252,206)', // 淡橙色
  495. 'gpt-3.5-turbo-16k-0613': 'rgb(119,255,214)', // 淡桃
  496. 'gpt-3.5-turbo-instruct': 'rgb(175,238,238)', // 粉蓝色
  497. 'gpt-4': 'rgb(135,206,235)', // 天蓝色
  498. // 'gpt-4-0314': 'rgb(70,130,180)', // 钢蓝色
  499. 'gpt-4-0613': 'rgb(100,149,237)', // 矢车菊蓝
  500. 'gpt-4-1106-preview': 'rgb(30,144,255)', // 道奇蓝
  501. 'gpt-4-0125-preview': 'rgb(2,177,236)', // 深天蓝
  502. 'gpt-4-turbo-preview': 'rgb(2,177,255)', // 深天蓝
  503. 'gpt-4-32k': 'rgb(104,111,238)', // 中紫色
  504. // 'gpt-4-32k-0314': 'rgb(90,105,205)', // 暗灰蓝色
  505. 'gpt-4-32k-0613': 'rgb(61,71,139)', // 暗蓝灰色
  506. 'gpt-4-all': 'rgb(65,105,225)', // 皇家蓝
  507. 'gpt-4-gizmo-*': 'rgb(0,0,255)', // 纯蓝色
  508. 'gpt-4-vision-preview': 'rgb(25,25,112)', // 午夜蓝
  509. 'text-ada-001': 'rgb(255,192,203)', // 粉红色
  510. 'text-babbage-001': 'rgb(255,160,122)', // 浅珊瑚色
  511. 'text-curie-001': 'rgb(219,112,147)', // 苍紫罗兰色
  512. // 'text-davinci-002': 'rgb(199,21,133)', // 中紫罗兰红色
  513. 'text-davinci-003': 'rgb(219,112,147)', // 苍紫罗兰色(与Curie相同,表示同一个系列)
  514. 'text-davinci-edit-001': 'rgb(255,105,180)', // 热粉色
  515. 'text-embedding-ada-002': 'rgb(255,182,193)', // 浅粉红
  516. 'text-embedding-v1': 'rgb(255,174,185)', // 浅粉红色(略有区别)
  517. 'text-moderation-latest': 'rgb(255,130,171)', // 强粉色
  518. 'text-moderation-stable': 'rgb(255,160,122)', // 浅珊瑚色(与Babbage相同,表示同一类功能)
  519. 'tts-1': 'rgb(255,140,0)', // 深橙色
  520. 'tts-1-1106': 'rgb(255,165,0)', // 橙色
  521. 'tts-1-hd': 'rgb(255,215,0)', // 金色
  522. 'tts-1-hd-1106': 'rgb(255,223,0)', // 金黄色(略有区别)
  523. 'whisper-1': 'rgb(245,245,220)', // 米色
  524. 'claude-3-opus-20240229': 'rgb(255,132,31)', // 橙红色
  525. 'claude-3-sonnet-20240229': 'rgb(253,135,93)', // 橙色
  526. 'claude-3-haiku-20240307': 'rgb(255,175,146)', // 浅橙色
  527. 'claude-2.1': 'rgb(255,209,190)', // 浅橙色(略有区别)
  528. };
  529. export function modelToColor(modelName) {
  530. // 1. 如果模型在预定义的 modelColorMap 中,使用预定义颜色
  531. if (modelColorMap[modelName]) {
  532. return modelColorMap[modelName];
  533. }
  534. // 2. 生成一个稳定的数字作为索引
  535. let hash = 0;
  536. for (let i = 0; i < modelName.length; i++) {
  537. hash = (hash << 5) - hash + modelName.charCodeAt(i);
  538. hash = hash & hash; // Convert to 32-bit integer
  539. }
  540. hash = Math.abs(hash);
  541. // 3. 根据模型名称长度选择不同的色板
  542. const colorPalette = modelName.length > 10 ? extendedColors : baseColors;
  543. // 4. 使用hash值选择颜色
  544. const index = hash % colorPalette.length;
  545. return colorPalette[index];
  546. }
  547. export function stringToColor(str) {
  548. let sum = 0;
  549. for (let i = 0; i < str.length; i++) {
  550. sum += str.charCodeAt(i);
  551. }
  552. let i = sum % colors.length;
  553. return colors[i];
  554. }
  555. // 渲染带有模型图标的标签
  556. export function renderModelTag(modelName, options = {}) {
  557. const {
  558. color,
  559. size = 'default',
  560. shape = 'circle',
  561. onClick,
  562. suffixIcon,
  563. } = options;
  564. const categories = getModelCategories(i18next.t);
  565. let icon = null;
  566. for (const [key, category] of Object.entries(categories)) {
  567. if (key !== 'all' && category.filter({ model_name: modelName })) {
  568. icon = category.icon;
  569. break;
  570. }
  571. }
  572. return (
  573. <Tag
  574. color={color || stringToColor(modelName)}
  575. prefixIcon={icon}
  576. suffixIcon={suffixIcon}
  577. size={size}
  578. shape={shape}
  579. onClick={onClick}
  580. >
  581. {modelName}
  582. </Tag>
  583. );
  584. }
  585. export function renderText(text, limit) {
  586. if (text.length > limit) {
  587. return text.slice(0, limit - 3) + '...';
  588. }
  589. return text;
  590. }
  591. /**
  592. * Render group tags based on the input group string
  593. * @param {string} group - The input group string
  594. * @returns {JSX.Element} - The rendered group tags
  595. */
  596. export function renderGroup(group) {
  597. if (group === '') {
  598. return (
  599. <Tag key='default' color='white' shape='circle'>
  600. {i18next.t('用户分组')}
  601. </Tag>
  602. );
  603. }
  604. const tagColors = {
  605. vip: 'yellow',
  606. pro: 'yellow',
  607. svip: 'red',
  608. premium: 'red',
  609. };
  610. const groups = group.split(',').sort();
  611. return (
  612. <span key={group}>
  613. {groups.map((group) => (
  614. <Tag
  615. color={tagColors[group] || stringToColor(group)}
  616. key={group}
  617. shape='circle'
  618. onClick={async (event) => {
  619. event.stopPropagation();
  620. if (await copy(group)) {
  621. showSuccess(i18next.t('已复制:') + group);
  622. } else {
  623. Modal.error({
  624. title: i18next.t('无法复制到剪贴板,请手动复制'),
  625. content: group,
  626. });
  627. }
  628. }}
  629. >
  630. {group}
  631. </Tag>
  632. ))}
  633. </span>
  634. );
  635. }
  636. export function renderRatio(ratio) {
  637. let color = 'green';
  638. if (ratio > 5) {
  639. color = 'red';
  640. } else if (ratio > 3) {
  641. color = 'orange';
  642. } else if (ratio > 1) {
  643. color = 'blue';
  644. }
  645. return (
  646. <Tag color={color}>
  647. {ratio}x {i18next.t('倍率')}
  648. </Tag>
  649. );
  650. }
  651. const measureTextWidth = (
  652. text,
  653. style = {
  654. fontSize: '14px',
  655. fontFamily:
  656. '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
  657. },
  658. containerWidth,
  659. ) => {
  660. const span = document.createElement('span');
  661. span.style.visibility = 'hidden';
  662. span.style.position = 'absolute';
  663. span.style.whiteSpace = 'nowrap';
  664. span.style.fontSize = style.fontSize;
  665. span.style.fontFamily = style.fontFamily;
  666. span.textContent = text;
  667. document.body.appendChild(span);
  668. const width = span.offsetWidth;
  669. document.body.removeChild(span);
  670. return width;
  671. };
  672. export function truncateText(text, maxWidth = 200) {
  673. const isMobileScreen = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`).matches;
  674. if (!isMobileScreen) {
  675. return text;
  676. }
  677. if (!text) return text;
  678. try {
  679. // Handle percentage-based maxWidth
  680. let actualMaxWidth = maxWidth;
  681. if (typeof maxWidth === 'string' && maxWidth.endsWith('%')) {
  682. const percentage = parseFloat(maxWidth) / 100;
  683. // Use window width as fallback container width
  684. actualMaxWidth = window.innerWidth * percentage;
  685. }
  686. const width = measureTextWidth(text);
  687. if (width <= actualMaxWidth) return text;
  688. let left = 0;
  689. let right = text.length;
  690. let result = text;
  691. while (left <= right) {
  692. const mid = Math.floor((left + right) / 2);
  693. const truncated = text.slice(0, mid) + '...';
  694. const currentWidth = measureTextWidth(truncated);
  695. if (currentWidth <= actualMaxWidth) {
  696. result = truncated;
  697. left = mid + 1;
  698. } else {
  699. right = mid - 1;
  700. }
  701. }
  702. return result;
  703. } catch (error) {
  704. console.warn(
  705. 'Text measurement failed, falling back to character count',
  706. error,
  707. );
  708. if (text.length > 20) {
  709. return text.slice(0, 17) + '...';
  710. }
  711. return text;
  712. }
  713. }
  714. export const renderGroupOption = (item) => {
  715. const {
  716. disabled,
  717. selected,
  718. label,
  719. value,
  720. focused,
  721. className,
  722. style,
  723. onMouseEnter,
  724. onClick,
  725. empty,
  726. emptyContent,
  727. ...rest
  728. } = item;
  729. const baseStyle = {
  730. display: 'flex',
  731. justifyContent: 'space-between',
  732. alignItems: 'center',
  733. padding: '8px 16px',
  734. cursor: disabled ? 'not-allowed' : 'pointer',
  735. backgroundColor: focused ? 'var(--semi-color-fill-0)' : 'transparent',
  736. opacity: disabled ? 0.5 : 1,
  737. ...(selected && {
  738. backgroundColor: 'var(--semi-color-primary-light-default)',
  739. }),
  740. '&:hover': {
  741. backgroundColor: !disabled && 'var(--semi-color-fill-1)',
  742. },
  743. };
  744. const handleClick = () => {
  745. if (!disabled && onClick) {
  746. onClick();
  747. }
  748. };
  749. const handleMouseEnter = (e) => {
  750. if (!disabled && onMouseEnter) {
  751. onMouseEnter(e);
  752. }
  753. };
  754. return (
  755. <div
  756. style={baseStyle}
  757. onClick={handleClick}
  758. onMouseEnter={handleMouseEnter}
  759. >
  760. <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
  761. <Typography.Text strong type={disabled ? 'tertiary' : undefined}>
  762. {value}
  763. </Typography.Text>
  764. <Typography.Text type='secondary' size='small'>
  765. {label}
  766. </Typography.Text>
  767. </div>
  768. {item.ratio && renderRatio(item.ratio)}
  769. </div>
  770. );
  771. };
  772. export function renderNumber(num) {
  773. if (num >= 1000000000) {
  774. return (num / 1000000000).toFixed(1) + 'B';
  775. } else if (num >= 1000000) {
  776. return (num / 1000000).toFixed(1) + 'M';
  777. } else if (num >= 10000) {
  778. return (num / 1000).toFixed(1) + 'k';
  779. } else {
  780. return num;
  781. }
  782. }
  783. export function renderQuotaNumberWithDigit(num, digits = 2) {
  784. if (typeof num !== 'number' || isNaN(num)) {
  785. return 0;
  786. }
  787. let displayInCurrency = localStorage.getItem('display_in_currency');
  788. num = num.toFixed(digits);
  789. if (displayInCurrency) {
  790. return '$' + num;
  791. }
  792. return num;
  793. }
  794. export function renderNumberWithPoint(num) {
  795. if (num === undefined) return '';
  796. num = num.toFixed(2);
  797. if (num >= 100000) {
  798. // Convert number to string to manipulate it
  799. let numStr = num.toString();
  800. // Find the position of the decimal point
  801. let decimalPointIndex = numStr.indexOf('.');
  802. let wholePart = numStr;
  803. let decimalPart = '';
  804. // If there is a decimal point, split the number into whole and decimal parts
  805. if (decimalPointIndex !== -1) {
  806. wholePart = numStr.slice(0, decimalPointIndex);
  807. decimalPart = numStr.slice(decimalPointIndex);
  808. }
  809. // Take the first two and last two digits of the whole number part
  810. let shortenedWholePart = wholePart.slice(0, 2) + '..' + wholePart.slice(-2);
  811. // Return the formatted number
  812. return shortenedWholePart + decimalPart;
  813. }
  814. // If the number is less than 100,000, return it unmodified
  815. return num;
  816. }
  817. export function getQuotaPerUnit() {
  818. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  819. quotaPerUnit = parseFloat(quotaPerUnit);
  820. return quotaPerUnit;
  821. }
  822. export function renderUnitWithQuota(quota) {
  823. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  824. quotaPerUnit = parseFloat(quotaPerUnit);
  825. quota = parseFloat(quota);
  826. return quotaPerUnit * quota;
  827. }
  828. export function getQuotaWithUnit(quota, digits = 6) {
  829. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  830. quotaPerUnit = parseFloat(quotaPerUnit);
  831. return (quota / quotaPerUnit).toFixed(digits);
  832. }
  833. export function renderQuotaWithAmount(amount) {
  834. let displayInCurrency = localStorage.getItem('display_in_currency');
  835. displayInCurrency = displayInCurrency === 'true';
  836. if (displayInCurrency) {
  837. return '$' + amount;
  838. } else {
  839. return renderNumber(renderUnitWithQuota(amount));
  840. }
  841. }
  842. export function renderQuota(quota, digits = 2) {
  843. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  844. let displayInCurrency = localStorage.getItem('display_in_currency');
  845. quotaPerUnit = parseFloat(quotaPerUnit);
  846. displayInCurrency = displayInCurrency === 'true';
  847. if (displayInCurrency) {
  848. const result = quota / quotaPerUnit;
  849. const fixedResult = result.toFixed(digits);
  850. // 如果 toFixed 后结果为 0 但原始值不为 0,显示最小值
  851. if (parseFloat(fixedResult) === 0 && quota > 0 && result > 0) {
  852. const minValue = Math.pow(10, -digits);
  853. return '$' + minValue.toFixed(digits);
  854. }
  855. return '$' + fixedResult;
  856. }
  857. return renderNumber(quota);
  858. }
  859. function isValidGroupRatio(ratio) {
  860. return Number.isFinite(ratio) && ratio !== -1;
  861. }
  862. /**
  863. * Helper function to get effective ratio and label
  864. * @param {number} groupRatio - The default group ratio
  865. * @param {number} user_group_ratio - The user-specific group ratio
  866. * @returns {Object} - Object containing { ratio, label, useUserGroupRatio }
  867. */
  868. function getEffectiveRatio(groupRatio, user_group_ratio) {
  869. const useUserGroupRatio = isValidGroupRatio(user_group_ratio);
  870. const ratioLabel = useUserGroupRatio
  871. ? i18next.t('专属倍率')
  872. : i18next.t('分组倍率');
  873. const effectiveRatio = useUserGroupRatio ? user_group_ratio : groupRatio;
  874. return {
  875. ratio: effectiveRatio,
  876. label: ratioLabel,
  877. useUserGroupRatio: useUserGroupRatio
  878. };
  879. }
  880. // Shared core for simple price rendering (used by OpenAI-like and Claude-like variants)
  881. function renderPriceSimpleCore({
  882. modelRatio,
  883. modelPrice = -1,
  884. groupRatio,
  885. user_group_ratio,
  886. cacheTokens = 0,
  887. cacheRatio = 1.0,
  888. cacheCreationTokens = 0,
  889. cacheCreationRatio = 1.0,
  890. image = false,
  891. imageRatio = 1.0,
  892. isSystemPromptOverride = false
  893. }) {
  894. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  895. groupRatio,
  896. user_group_ratio,
  897. );
  898. const finalGroupRatio = effectiveGroupRatio;
  899. if (modelPrice !== -1) {
  900. return i18next.t('价格:${{price}} * {{ratioType}}:{{ratio}}', {
  901. price: modelPrice,
  902. ratioType: ratioLabel,
  903. ratio: finalGroupRatio,
  904. });
  905. }
  906. const parts = [];
  907. // base: model ratio
  908. parts.push(i18next.t('模型: {{ratio}}'));
  909. // cache part (label differs when with image)
  910. if (cacheTokens !== 0) {
  911. parts.push(i18next.t('缓存: {{cacheRatio}}'));
  912. }
  913. // cache creation part (Claude specific if passed)
  914. if (cacheCreationTokens !== 0) {
  915. parts.push(i18next.t('缓存创建: {{cacheCreationRatio}}'));
  916. }
  917. // image part
  918. if (image) {
  919. parts.push(i18next.t('图片输入: {{imageRatio}}'));
  920. }
  921. parts.push(`{{ratioType}}: {{groupRatio}}`);
  922. let result = i18next.t(parts.join(' * '), {
  923. ratio: modelRatio,
  924. ratioType: ratioLabel,
  925. groupRatio: finalGroupRatio,
  926. cacheRatio: cacheRatio,
  927. cacheCreationRatio: cacheCreationRatio,
  928. imageRatio: imageRatio,
  929. })
  930. if (isSystemPromptOverride) {
  931. result += '\n\r' + i18next.t('系统提示覆盖');
  932. }
  933. return result;
  934. }
  935. export function renderModelPrice(
  936. inputTokens,
  937. completionTokens,
  938. modelRatio,
  939. modelPrice = -1,
  940. completionRatio,
  941. groupRatio,
  942. user_group_ratio,
  943. cacheTokens = 0,
  944. cacheRatio = 1.0,
  945. image = false,
  946. imageRatio = 1.0,
  947. imageOutputTokens = 0,
  948. webSearch = false,
  949. webSearchCallCount = 0,
  950. webSearchPrice = 0,
  951. fileSearch = false,
  952. fileSearchCallCount = 0,
  953. fileSearchPrice = 0,
  954. audioInputSeperatePrice = false,
  955. audioInputTokens = 0,
  956. audioInputPrice = 0,
  957. ) {
  958. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(groupRatio, user_group_ratio);
  959. groupRatio = effectiveGroupRatio;
  960. if (modelPrice !== -1) {
  961. return i18next.t(
  962. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  963. {
  964. price: modelPrice,
  965. ratio: groupRatio,
  966. total: modelPrice * groupRatio,
  967. ratioType: ratioLabel,
  968. },
  969. );
  970. } else {
  971. if (completionRatio === undefined) {
  972. completionRatio = 0;
  973. }
  974. let inputRatioPrice = modelRatio * 2.0;
  975. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  976. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  977. let imageRatioPrice = modelRatio * 2.0 * imageRatio;
  978. // Calculate effective input tokens (non-cached + cached with ratio applied)
  979. let effectiveInputTokens =
  980. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  981. // Handle image tokens if present
  982. if (image && imageOutputTokens > 0) {
  983. effectiveInputTokens =
  984. inputTokens - imageOutputTokens + imageOutputTokens * imageRatio;
  985. }
  986. if (audioInputTokens > 0) {
  987. effectiveInputTokens -= audioInputTokens;
  988. }
  989. let price =
  990. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  991. (audioInputTokens / 1000000) * audioInputPrice * groupRatio +
  992. (completionTokens / 1000000) * completionRatioPrice * groupRatio +
  993. (webSearchCallCount / 1000) * webSearchPrice * groupRatio +
  994. (fileSearchCallCount / 1000) * fileSearchPrice * groupRatio;
  995. return (
  996. <>
  997. <article>
  998. <p>
  999. {i18next.t('输入价格:${{price}} / 1M tokens{{audioPrice}}', {
  1000. price: inputRatioPrice,
  1001. audioPrice: audioInputSeperatePrice
  1002. ? `,音频 $${audioInputPrice} / 1M tokens`
  1003. : '',
  1004. })}
  1005. </p>
  1006. <p>
  1007. {i18next.t(
  1008. '输出价格:${{price}} * {{completionRatio}} = ${{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1009. {
  1010. price: inputRatioPrice,
  1011. total: completionRatioPrice,
  1012. completionRatio: completionRatio,
  1013. },
  1014. )}
  1015. </p>
  1016. {cacheTokens > 0 && (
  1017. <p>
  1018. {i18next.t(
  1019. '缓存价格:${{price}} * {{cacheRatio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1020. {
  1021. price: inputRatioPrice,
  1022. total: inputRatioPrice * cacheRatio,
  1023. cacheRatio: cacheRatio,
  1024. },
  1025. )}
  1026. </p>
  1027. )}
  1028. {image && imageOutputTokens > 0 && (
  1029. <p>
  1030. {i18next.t(
  1031. '图片输入价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (图片倍率: {{imageRatio}})',
  1032. {
  1033. price: imageRatioPrice,
  1034. ratio: groupRatio,
  1035. total: imageRatioPrice * groupRatio,
  1036. imageRatio: imageRatio,
  1037. },
  1038. )}
  1039. </p>
  1040. )}
  1041. {webSearch && webSearchCallCount > 0 && (
  1042. <p>
  1043. {i18next.t('Web搜索价格:${{price}} / 1K 次', {
  1044. price: webSearchPrice,
  1045. })}
  1046. </p>
  1047. )}
  1048. {fileSearch && fileSearchCallCount > 0 && (
  1049. <p>
  1050. {i18next.t('文件搜索价格:${{price}} / 1K 次', {
  1051. price: fileSearchPrice,
  1052. })}
  1053. </p>
  1054. )}
  1055. <p></p>
  1056. <p>
  1057. {(() => {
  1058. // 构建输入部分描述
  1059. let inputDesc = '';
  1060. if (image && imageOutputTokens > 0) {
  1061. inputDesc = i18next.t(
  1062. '(输入 {{nonImageInput}} tokens + 图片输入 {{imageInput}} tokens * {{imageRatio}} / 1M tokens * ${{price}}',
  1063. {
  1064. nonImageInput: inputTokens - imageOutputTokens,
  1065. imageInput: imageOutputTokens,
  1066. imageRatio: imageRatio,
  1067. price: inputRatioPrice,
  1068. },
  1069. );
  1070. } else if (cacheTokens > 0) {
  1071. inputDesc = i18next.t(
  1072. '(输入 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}}',
  1073. {
  1074. nonCacheInput: inputTokens - cacheTokens,
  1075. cacheInput: cacheTokens,
  1076. price: inputRatioPrice,
  1077. cachePrice: cacheRatioPrice,
  1078. },
  1079. );
  1080. } else if (audioInputSeperatePrice && audioInputTokens > 0) {
  1081. inputDesc = i18next.t(
  1082. '(输入 {{nonAudioInput}} tokens / 1M tokens * ${{price}} + 音频输入 {{audioInput}} tokens / 1M tokens * ${{audioPrice}}',
  1083. {
  1084. nonAudioInput: inputTokens - audioInputTokens,
  1085. audioInput: audioInputTokens,
  1086. price: inputRatioPrice,
  1087. audioPrice: audioInputPrice,
  1088. },
  1089. );
  1090. } else {
  1091. inputDesc = i18next.t(
  1092. '(输入 {{input}} tokens / 1M tokens * ${{price}}',
  1093. {
  1094. input: inputTokens,
  1095. price: inputRatioPrice,
  1096. },
  1097. );
  1098. }
  1099. // 构建输出部分描述
  1100. const outputDesc = i18next.t(
  1101. '输出 {{completion}} tokens / 1M tokens * ${{compPrice}}) * {{ratioType}} {{ratio}}',
  1102. {
  1103. completion: completionTokens,
  1104. compPrice: completionRatioPrice,
  1105. ratio: groupRatio,
  1106. ratioType: ratioLabel,
  1107. },
  1108. );
  1109. // 构建额外服务描述
  1110. const extraServices = [
  1111. webSearch && webSearchCallCount > 0
  1112. ? i18next.t(
  1113. ' + Web搜索 {{count}}次 / 1K 次 * ${{price}} * {{ratioType}} {{ratio}}',
  1114. {
  1115. count: webSearchCallCount,
  1116. price: webSearchPrice,
  1117. ratio: groupRatio,
  1118. ratioType: ratioLabel,
  1119. },
  1120. )
  1121. : '',
  1122. fileSearch && fileSearchCallCount > 0
  1123. ? i18next.t(
  1124. ' + 文件搜索 {{count}}次 / 1K 次 * ${{price}} * {{ratioType}} {{ratio}}',
  1125. {
  1126. count: fileSearchCallCount,
  1127. price: fileSearchPrice,
  1128. ratio: groupRatio,
  1129. ratioType: ratioLabel,
  1130. },
  1131. )
  1132. : '',
  1133. ].join('');
  1134. return i18next.t(
  1135. '{{inputDesc}} + {{outputDesc}}{{extraServices}} = ${{total}}',
  1136. {
  1137. inputDesc,
  1138. outputDesc,
  1139. extraServices,
  1140. total: price.toFixed(6),
  1141. },
  1142. );
  1143. })()}
  1144. </p>
  1145. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1146. </article>
  1147. </>
  1148. );
  1149. }
  1150. }
  1151. export function renderLogContent(
  1152. modelRatio,
  1153. completionRatio,
  1154. modelPrice = -1,
  1155. groupRatio,
  1156. user_group_ratio,
  1157. cacheRatio = 1.0,
  1158. image = false,
  1159. imageRatio = 1.0,
  1160. webSearch = false,
  1161. webSearchCallCount = 0,
  1162. fileSearch = false,
  1163. fileSearchCallCount = 0,
  1164. ) {
  1165. const { ratio, label: ratioLabel, useUserGroupRatio: useUserGroupRatio } = getEffectiveRatio(groupRatio, user_group_ratio);
  1166. if (modelPrice !== -1) {
  1167. return i18next.t('模型价格 ${{price}},{{ratioType}} {{ratio}}', {
  1168. price: modelPrice,
  1169. ratioType: ratioLabel,
  1170. ratio,
  1171. });
  1172. } else {
  1173. if (image) {
  1174. return i18next.t(
  1175. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},图片输入倍率 {{imageRatio}},{{ratioType}} {{ratio}}',
  1176. {
  1177. modelRatio: modelRatio,
  1178. cacheRatio: cacheRatio,
  1179. completionRatio: completionRatio,
  1180. imageRatio: imageRatio,
  1181. ratioType: ratioLabel,
  1182. ratio,
  1183. },
  1184. );
  1185. } else if (webSearch) {
  1186. return i18next.t(
  1187. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}},Web 搜索调用 {{webSearchCallCount}} 次',
  1188. {
  1189. modelRatio: modelRatio,
  1190. cacheRatio: cacheRatio,
  1191. completionRatio: completionRatio,
  1192. ratioType: ratioLabel,
  1193. ratio,
  1194. webSearchCallCount,
  1195. },
  1196. );
  1197. } else {
  1198. return i18next.t(
  1199. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}}',
  1200. {
  1201. modelRatio: modelRatio,
  1202. cacheRatio: cacheRatio,
  1203. completionRatio: completionRatio,
  1204. ratioType: ratioLabel,
  1205. ratio,
  1206. },
  1207. );
  1208. }
  1209. }
  1210. }
  1211. export function renderModelPriceSimple(
  1212. modelRatio,
  1213. modelPrice = -1,
  1214. groupRatio,
  1215. user_group_ratio,
  1216. cacheTokens = 0,
  1217. cacheRatio = 1.0,
  1218. cacheCreationTokens = 0,
  1219. cacheCreationRatio = 1.0,
  1220. image = false,
  1221. imageRatio = 1.0,
  1222. isSystemPromptOverride = false,
  1223. provider = 'openai',
  1224. ) {
  1225. return renderPriceSimpleCore({
  1226. modelRatio,
  1227. modelPrice,
  1228. groupRatio,
  1229. user_group_ratio,
  1230. cacheTokens,
  1231. cacheRatio,
  1232. cacheCreationTokens,
  1233. cacheCreationRatio,
  1234. image,
  1235. imageRatio,
  1236. isSystemPromptOverride
  1237. });
  1238. }
  1239. export function renderAudioModelPrice(
  1240. inputTokens,
  1241. completionTokens,
  1242. modelRatio,
  1243. modelPrice = -1,
  1244. completionRatio,
  1245. audioInputTokens,
  1246. audioCompletionTokens,
  1247. audioRatio,
  1248. audioCompletionRatio,
  1249. groupRatio,
  1250. user_group_ratio,
  1251. cacheTokens = 0,
  1252. cacheRatio = 1.0,
  1253. ) {
  1254. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(groupRatio, user_group_ratio);
  1255. groupRatio = effectiveGroupRatio;
  1256. // 1 ratio = $0.002 / 1K tokens
  1257. if (modelPrice !== -1) {
  1258. return i18next.t(
  1259. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  1260. {
  1261. price: modelPrice,
  1262. ratio: groupRatio,
  1263. total: modelPrice * groupRatio,
  1264. ratioType: ratioLabel,
  1265. },
  1266. );
  1267. } else {
  1268. if (completionRatio === undefined) {
  1269. completionRatio = 0;
  1270. }
  1271. // try toFixed audioRatio
  1272. audioRatio = parseFloat(audioRatio).toFixed(6);
  1273. // 这里的 *2 是因为 1倍率=0.002刀,请勿删除
  1274. let inputRatioPrice = modelRatio * 2.0;
  1275. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  1276. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  1277. // Calculate effective input tokens (non-cached + cached with ratio applied)
  1278. const effectiveInputTokens =
  1279. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  1280. let textPrice =
  1281. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1282. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1283. let audioPrice =
  1284. (audioInputTokens / 1000000) * inputRatioPrice * audioRatio * groupRatio +
  1285. (audioCompletionTokens / 1000000) *
  1286. inputRatioPrice *
  1287. audioRatio *
  1288. audioCompletionRatio *
  1289. groupRatio;
  1290. let price = textPrice + audioPrice;
  1291. return (
  1292. <>
  1293. <article>
  1294. <p>
  1295. {i18next.t('提示价格:${{price}} / 1M tokens', {
  1296. price: inputRatioPrice,
  1297. })}
  1298. </p>
  1299. <p>
  1300. {i18next.t(
  1301. '补全价格:${{price}} * {{completionRatio}} = ${{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1302. {
  1303. price: inputRatioPrice,
  1304. total: completionRatioPrice,
  1305. completionRatio: completionRatio,
  1306. },
  1307. )}
  1308. </p>
  1309. {cacheTokens > 0 && (
  1310. <p>
  1311. {i18next.t(
  1312. '缓存价格:${{price}} * {{cacheRatio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1313. {
  1314. price: inputRatioPrice,
  1315. total: inputRatioPrice * cacheRatio,
  1316. cacheRatio: cacheRatio,
  1317. },
  1318. )}
  1319. </p>
  1320. )}
  1321. <p>
  1322. {i18next.t(
  1323. '音频提示价格:${{price}} * {{audioRatio}} = ${{total}} / 1M tokens (音频倍率: {{audioRatio}})',
  1324. {
  1325. price: inputRatioPrice,
  1326. total: inputRatioPrice * audioRatio,
  1327. audioRatio: audioRatio,
  1328. },
  1329. )}
  1330. </p>
  1331. <p>
  1332. {i18next.t(
  1333. '音频补全价格:${{price}} * {{audioRatio}} * {{audioCompRatio}} = ${{total}} / 1M tokens (音频补全倍率: {{audioCompRatio}})',
  1334. {
  1335. price: inputRatioPrice,
  1336. total: inputRatioPrice * audioRatio * audioCompletionRatio,
  1337. audioRatio: audioRatio,
  1338. audioCompRatio: audioCompletionRatio,
  1339. },
  1340. )}
  1341. </p>
  1342. <p>
  1343. {cacheTokens > 0
  1344. ? i18next.t(
  1345. '文字提示 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}} + 文字补全 {{completion}} tokens / 1M tokens * ${{compPrice}} = ${{total}}',
  1346. {
  1347. nonCacheInput: inputTokens - cacheTokens,
  1348. cacheInput: cacheTokens,
  1349. cachePrice: inputRatioPrice * cacheRatio,
  1350. price: inputRatioPrice,
  1351. completion: completionTokens,
  1352. compPrice: completionRatioPrice,
  1353. total: textPrice.toFixed(6),
  1354. },
  1355. )
  1356. : i18next.t(
  1357. '文字提示 {{input}} tokens / 1M tokens * ${{price}} + 文字补全 {{completion}} tokens / 1M tokens * ${{compPrice}} = ${{total}}',
  1358. {
  1359. input: inputTokens,
  1360. price: inputRatioPrice,
  1361. completion: completionTokens,
  1362. compPrice: completionRatioPrice,
  1363. total: textPrice.toFixed(6),
  1364. },
  1365. )}
  1366. </p>
  1367. <p>
  1368. {i18next.t(
  1369. '音频提示 {{input}} tokens / 1M tokens * ${{audioInputPrice}} + 音频补全 {{completion}} tokens / 1M tokens * ${{audioCompPrice}} = ${{total}}',
  1370. {
  1371. input: audioInputTokens,
  1372. completion: audioCompletionTokens,
  1373. audioInputPrice: audioRatio * inputRatioPrice,
  1374. audioCompPrice:
  1375. audioRatio * audioCompletionRatio * inputRatioPrice,
  1376. total: audioPrice.toFixed(6),
  1377. },
  1378. )}
  1379. </p>
  1380. <p>
  1381. {i18next.t(
  1382. '总价:文字价格 {{textPrice}} + 音频价格 {{audioPrice}} = ${{total}}',
  1383. {
  1384. total: price.toFixed(6),
  1385. textPrice: textPrice.toFixed(6),
  1386. audioPrice: audioPrice.toFixed(6),
  1387. },
  1388. )}
  1389. </p>
  1390. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1391. </article>
  1392. </>
  1393. );
  1394. }
  1395. }
  1396. export function renderQuotaWithPrompt(quota, digits) {
  1397. let displayInCurrency = localStorage.getItem('display_in_currency');
  1398. displayInCurrency = displayInCurrency === 'true';
  1399. if (displayInCurrency) {
  1400. return (
  1401. i18next.t('等价金额:') + renderQuota(quota, digits)
  1402. );
  1403. }
  1404. return '';
  1405. }
  1406. export function renderClaudeModelPrice(
  1407. inputTokens,
  1408. completionTokens,
  1409. modelRatio,
  1410. modelPrice = -1,
  1411. completionRatio,
  1412. groupRatio,
  1413. user_group_ratio,
  1414. cacheTokens = 0,
  1415. cacheRatio = 1.0,
  1416. cacheCreationTokens = 0,
  1417. cacheCreationRatio = 1.0,
  1418. ) {
  1419. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(groupRatio, user_group_ratio);
  1420. groupRatio = effectiveGroupRatio;
  1421. if (modelPrice !== -1) {
  1422. return i18next.t(
  1423. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  1424. {
  1425. price: modelPrice,
  1426. ratioType: ratioLabel,
  1427. ratio: groupRatio,
  1428. total: modelPrice * groupRatio,
  1429. },
  1430. );
  1431. } else {
  1432. if (completionRatio === undefined) {
  1433. completionRatio = 0;
  1434. }
  1435. const completionRatioValue = completionRatio || 0;
  1436. const inputRatioPrice = modelRatio * 2.0;
  1437. const completionRatioPrice = modelRatio * 2.0 * completionRatioValue;
  1438. let cacheRatioPrice = (modelRatio * 2.0 * cacheRatio).toFixed(2);
  1439. let cacheCreationRatioPrice = modelRatio * 2.0 * cacheCreationRatio;
  1440. // Calculate effective input tokens (non-cached + cached with ratio applied + cache creation with ratio applied)
  1441. const nonCachedTokens = inputTokens;
  1442. const effectiveInputTokens =
  1443. nonCachedTokens +
  1444. cacheTokens * cacheRatio +
  1445. cacheCreationTokens * cacheCreationRatio;
  1446. let price =
  1447. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1448. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1449. return (
  1450. <>
  1451. <article>
  1452. <p>
  1453. {i18next.t('提示价格:${{price}} / 1M tokens', {
  1454. price: inputRatioPrice,
  1455. })}
  1456. </p>
  1457. <p>
  1458. {i18next.t(
  1459. '补全价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens',
  1460. {
  1461. price: inputRatioPrice,
  1462. ratio: completionRatio,
  1463. total: completionRatioPrice,
  1464. },
  1465. )}
  1466. </p>
  1467. {cacheTokens > 0 && (
  1468. <p>
  1469. {i18next.t(
  1470. '缓存价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1471. {
  1472. price: inputRatioPrice,
  1473. ratio: cacheRatio,
  1474. total: cacheRatioPrice,
  1475. cacheRatio: cacheRatio,
  1476. },
  1477. )}
  1478. </p>
  1479. )}
  1480. {cacheCreationTokens > 0 && (
  1481. <p>
  1482. {i18next.t(
  1483. '缓存创建价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (缓存创建倍率: {{cacheCreationRatio}})',
  1484. {
  1485. price: inputRatioPrice,
  1486. ratio: cacheCreationRatio,
  1487. total: cacheCreationRatioPrice,
  1488. cacheCreationRatio: cacheCreationRatio,
  1489. },
  1490. )}
  1491. </p>
  1492. )}
  1493. <p></p>
  1494. <p>
  1495. {cacheTokens > 0 || cacheCreationTokens > 0
  1496. ? i18next.t(
  1497. '提示 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}} + 缓存创建 {{cacheCreationInput}} tokens / 1M tokens * ${{cacheCreationPrice}} + 补全 {{completion}} tokens / 1M tokens * ${{compPrice}} * {{ratioType}} {{ratio}} = ${{total}}',
  1498. {
  1499. nonCacheInput: nonCachedTokens,
  1500. cacheInput: cacheTokens,
  1501. cacheRatio: cacheRatio,
  1502. cacheCreationInput: cacheCreationTokens,
  1503. cacheCreationRatio: cacheCreationRatio,
  1504. cachePrice: cacheRatioPrice,
  1505. cacheCreationPrice: cacheCreationRatioPrice,
  1506. price: inputRatioPrice,
  1507. completion: completionTokens,
  1508. compPrice: completionRatioPrice,
  1509. ratio: groupRatio,
  1510. ratioType: ratioLabel,
  1511. total: price.toFixed(6),
  1512. },
  1513. )
  1514. : i18next.t(
  1515. '提示 {{input}} tokens / 1M tokens * ${{price}} + 补全 {{completion}} tokens / 1M tokens * ${{compPrice}} * {{ratioType}} {{ratio}} = ${{total}}',
  1516. {
  1517. input: inputTokens,
  1518. price: inputRatioPrice,
  1519. completion: completionTokens,
  1520. compPrice: completionRatioPrice,
  1521. ratio: groupRatio,
  1522. ratioType: ratioLabel,
  1523. total: price.toFixed(6),
  1524. },
  1525. )}
  1526. </p>
  1527. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1528. </article>
  1529. </>
  1530. );
  1531. }
  1532. }
  1533. export function renderClaudeLogContent(
  1534. modelRatio,
  1535. completionRatio,
  1536. modelPrice = -1,
  1537. groupRatio,
  1538. user_group_ratio,
  1539. cacheRatio = 1.0,
  1540. cacheCreationRatio = 1.0,
  1541. ) {
  1542. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(groupRatio, user_group_ratio);
  1543. groupRatio = effectiveGroupRatio;
  1544. if (modelPrice !== -1) {
  1545. return i18next.t('模型价格 ${{price}},{{ratioType}} {{ratio}}', {
  1546. price: modelPrice,
  1547. ratioType: ratioLabel,
  1548. ratio: groupRatio,
  1549. });
  1550. } else {
  1551. return i18next.t(
  1552. '模型倍率 {{modelRatio}},输出倍率 {{completionRatio}},缓存倍率 {{cacheRatio}},缓存创建倍率 {{cacheCreationRatio}},{{ratioType}} {{ratio}}',
  1553. {
  1554. modelRatio: modelRatio,
  1555. completionRatio: completionRatio,
  1556. cacheRatio: cacheRatio,
  1557. cacheCreationRatio: cacheCreationRatio,
  1558. ratioType: ratioLabel,
  1559. ratio: groupRatio,
  1560. },
  1561. );
  1562. }
  1563. }
  1564. // 已统一至 renderModelPriceSimple,若仍有遗留引用,请改为传入 provider='claude'
  1565. /**
  1566. * rehype 插件:将段落等文本节点拆分为逐词 <span>,并添加淡入动画 class。
  1567. * 仅在流式渲染阶段使用,避免已渲染文字重复动画。
  1568. */
  1569. export function rehypeSplitWordsIntoSpans(options = {}) {
  1570. const { previousContentLength = 0 } = options;
  1571. return (tree) => {
  1572. let currentCharCount = 0; // 当前已处理的字符数
  1573. visit(tree, 'element', (node) => {
  1574. if (
  1575. ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'strong'].includes(
  1576. node.tagName,
  1577. ) &&
  1578. node.children
  1579. ) {
  1580. const newChildren = [];
  1581. node.children.forEach((child) => {
  1582. if (child.type === 'text') {
  1583. try {
  1584. // 使用 Intl.Segmenter 精准拆分中英文及标点
  1585. const segmenter = new Intl.Segmenter('zh', {
  1586. granularity: 'word',
  1587. });
  1588. const segments = segmenter.segment(child.value);
  1589. Array.from(segments)
  1590. .map((seg) => seg.segment)
  1591. .filter(Boolean)
  1592. .forEach((word) => {
  1593. const wordStartPos = currentCharCount;
  1594. const wordEndPos = currentCharCount + word.length;
  1595. // 判断这个词是否是新增的(在 previousContentLength 之后)
  1596. const isNewContent = wordStartPos >= previousContentLength;
  1597. newChildren.push({
  1598. type: 'element',
  1599. tagName: 'span',
  1600. properties: {
  1601. className: isNewContent ? ['animate-fade-in'] : [],
  1602. },
  1603. children: [{ type: 'text', value: word }],
  1604. });
  1605. currentCharCount = wordEndPos;
  1606. });
  1607. } catch (_) {
  1608. // Fallback:如果浏览器不支持 Segmenter
  1609. const textStartPos = currentCharCount;
  1610. const isNewContent = textStartPos >= previousContentLength;
  1611. if (isNewContent) {
  1612. // 新内容,添加动画
  1613. newChildren.push({
  1614. type: 'element',
  1615. tagName: 'span',
  1616. properties: {
  1617. className: ['animate-fade-in'],
  1618. },
  1619. children: [{ type: 'text', value: child.value }],
  1620. });
  1621. } else {
  1622. // 旧内容,不添加动画
  1623. newChildren.push(child);
  1624. }
  1625. currentCharCount += child.value.length;
  1626. }
  1627. } else {
  1628. newChildren.push(child);
  1629. }
  1630. });
  1631. node.children = newChildren;
  1632. }
  1633. });
  1634. };
  1635. }