render.jsx 52 KB

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