render.jsx 53 KB

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