render.jsx 59 KB

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