render.js 50 KB

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