render.jsx 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  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. imageGenerationCall = false,
  944. imageGenerationCallPrice = 0,
  945. ) {
  946. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  947. groupRatio,
  948. user_group_ratio,
  949. );
  950. groupRatio = effectiveGroupRatio;
  951. if (modelPrice !== -1) {
  952. return i18next.t(
  953. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  954. {
  955. price: modelPrice,
  956. ratio: groupRatio,
  957. total: modelPrice * groupRatio,
  958. ratioType: ratioLabel,
  959. },
  960. );
  961. } else {
  962. if (completionRatio === undefined) {
  963. completionRatio = 0;
  964. }
  965. let inputRatioPrice = modelRatio * 2.0;
  966. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  967. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  968. let imageRatioPrice = modelRatio * 2.0 * imageRatio;
  969. // Calculate effective input tokens (non-cached + cached with ratio applied)
  970. let effectiveInputTokens =
  971. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  972. // Handle image tokens if present
  973. if (image && imageOutputTokens > 0) {
  974. effectiveInputTokens =
  975. inputTokens - imageOutputTokens + imageOutputTokens * imageRatio;
  976. }
  977. if (audioInputTokens > 0) {
  978. effectiveInputTokens -= audioInputTokens;
  979. }
  980. let price =
  981. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  982. (audioInputTokens / 1000000) * audioInputPrice * groupRatio +
  983. (completionTokens / 1000000) * completionRatioPrice * groupRatio +
  984. (webSearchCallCount / 1000) * webSearchPrice * groupRatio +
  985. (fileSearchCallCount / 1000) * fileSearchPrice * groupRatio +
  986. (imageGenerationCallPrice * groupRatio);
  987. return (
  988. <>
  989. <article>
  990. <p>
  991. {i18next.t('输入价格:${{price}} / 1M tokens{{audioPrice}}', {
  992. price: inputRatioPrice,
  993. audioPrice: audioInputSeperatePrice
  994. ? `,音频 $${audioInputPrice} / 1M tokens`
  995. : '',
  996. })}
  997. </p>
  998. <p>
  999. {i18next.t(
  1000. '输出价格:${{price}} * {{completionRatio}} = ${{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1001. {
  1002. price: inputRatioPrice,
  1003. total: completionRatioPrice,
  1004. completionRatio: completionRatio,
  1005. },
  1006. )}
  1007. </p>
  1008. {cacheTokens > 0 && (
  1009. <p>
  1010. {i18next.t(
  1011. '缓存价格:${{price}} * {{cacheRatio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1012. {
  1013. price: inputRatioPrice,
  1014. total: inputRatioPrice * cacheRatio,
  1015. cacheRatio: cacheRatio,
  1016. },
  1017. )}
  1018. </p>
  1019. )}
  1020. {image && imageOutputTokens > 0 && (
  1021. <p>
  1022. {i18next.t(
  1023. '图片输入价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (图片倍率: {{imageRatio}})',
  1024. {
  1025. price: imageRatioPrice,
  1026. ratio: groupRatio,
  1027. total: imageRatioPrice * groupRatio,
  1028. imageRatio: imageRatio,
  1029. },
  1030. )}
  1031. </p>
  1032. )}
  1033. {webSearch && webSearchCallCount > 0 && (
  1034. <p>
  1035. {i18next.t('Web搜索价格:${{price}} / 1K 次', {
  1036. price: webSearchPrice,
  1037. })}
  1038. </p>
  1039. )}
  1040. {fileSearch && fileSearchCallCount > 0 && (
  1041. <p>
  1042. {i18next.t('文件搜索价格:${{price}} / 1K 次', {
  1043. price: fileSearchPrice,
  1044. })}
  1045. </p>
  1046. )}
  1047. {imageGenerationCall && imageGenerationCallPrice > 0 && (
  1048. <p>
  1049. {i18next.t('图片生成调用:${{price}} / 1次', {
  1050. price: imageGenerationCallPrice,
  1051. })}
  1052. </p>
  1053. )}
  1054. <p>
  1055. {(() => {
  1056. // 构建输入部分描述
  1057. let inputDesc = '';
  1058. if (image && imageOutputTokens > 0) {
  1059. inputDesc = i18next.t(
  1060. '(输入 {{nonImageInput}} tokens + 图片输入 {{imageInput}} tokens * {{imageRatio}} / 1M tokens * ${{price}}',
  1061. {
  1062. nonImageInput: inputTokens - imageOutputTokens,
  1063. imageInput: imageOutputTokens,
  1064. imageRatio: imageRatio,
  1065. price: inputRatioPrice,
  1066. },
  1067. );
  1068. } else if (cacheTokens > 0) {
  1069. inputDesc = i18next.t(
  1070. '(输入 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}}',
  1071. {
  1072. nonCacheInput: inputTokens - cacheTokens,
  1073. cacheInput: cacheTokens,
  1074. price: inputRatioPrice,
  1075. cachePrice: cacheRatioPrice,
  1076. },
  1077. );
  1078. } else if (audioInputSeperatePrice && audioInputTokens > 0) {
  1079. inputDesc = i18next.t(
  1080. '(输入 {{nonAudioInput}} tokens / 1M tokens * ${{price}} + 音频输入 {{audioInput}} tokens / 1M tokens * ${{audioPrice}}',
  1081. {
  1082. nonAudioInput: inputTokens - audioInputTokens,
  1083. audioInput: audioInputTokens,
  1084. price: inputRatioPrice,
  1085. audioPrice: audioInputPrice,
  1086. },
  1087. );
  1088. } else {
  1089. inputDesc = i18next.t(
  1090. '(输入 {{input}} tokens / 1M tokens * ${{price}}',
  1091. {
  1092. input: inputTokens,
  1093. price: inputRatioPrice,
  1094. },
  1095. );
  1096. }
  1097. // 构建输出部分描述
  1098. const outputDesc = i18next.t(
  1099. '输出 {{completion}} tokens / 1M tokens * ${{compPrice}}) * {{ratioType}} {{ratio}}',
  1100. {
  1101. completion: completionTokens,
  1102. compPrice: completionRatioPrice,
  1103. ratio: groupRatio,
  1104. ratioType: ratioLabel,
  1105. },
  1106. );
  1107. // 构建额外服务描述
  1108. const extraServices = [
  1109. webSearch && webSearchCallCount > 0
  1110. ? i18next.t(
  1111. ' + Web搜索 {{count}}次 / 1K 次 * ${{price}} * {{ratioType}} {{ratio}}',
  1112. {
  1113. count: webSearchCallCount,
  1114. price: webSearchPrice,
  1115. ratio: groupRatio,
  1116. ratioType: ratioLabel,
  1117. },
  1118. )
  1119. : '',
  1120. fileSearch && fileSearchCallCount > 0
  1121. ? i18next.t(
  1122. ' + 文件搜索 {{count}}次 / 1K 次 * ${{price}} * {{ratioType}} {{ratio}}',
  1123. {
  1124. count: fileSearchCallCount,
  1125. price: fileSearchPrice,
  1126. ratio: groupRatio,
  1127. ratioType: ratioLabel,
  1128. },
  1129. )
  1130. : '',
  1131. imageGenerationCall && imageGenerationCallPrice > 0
  1132. ? i18next.t(
  1133. ' + 图片生成调用 ${{price}} / 1次 * {{ratioType}} {{ratio}}',
  1134. {
  1135. price: imageGenerationCallPrice,
  1136. ratio: groupRatio,
  1137. ratioType: ratioLabel,
  1138. },
  1139. )
  1140. : '',
  1141. ].join('');
  1142. return i18next.t(
  1143. '{{inputDesc}} + {{outputDesc}}{{extraServices}} = ${{total}}',
  1144. {
  1145. inputDesc,
  1146. outputDesc,
  1147. extraServices,
  1148. total: price.toFixed(6),
  1149. },
  1150. );
  1151. })()}
  1152. </p>
  1153. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1154. </article>
  1155. </>
  1156. );
  1157. }
  1158. }
  1159. export function renderLogContent(
  1160. modelRatio,
  1161. completionRatio,
  1162. modelPrice = -1,
  1163. groupRatio,
  1164. user_group_ratio,
  1165. cacheRatio = 1.0,
  1166. image = false,
  1167. imageRatio = 1.0,
  1168. webSearch = false,
  1169. webSearchCallCount = 0,
  1170. fileSearch = false,
  1171. fileSearchCallCount = 0,
  1172. ) {
  1173. const {
  1174. ratio,
  1175. label: ratioLabel,
  1176. useUserGroupRatio: useUserGroupRatio,
  1177. } = getEffectiveRatio(groupRatio, user_group_ratio);
  1178. if (modelPrice !== -1) {
  1179. return i18next.t('模型价格 ${{price}},{{ratioType}} {{ratio}}', {
  1180. price: modelPrice,
  1181. ratioType: ratioLabel,
  1182. ratio,
  1183. });
  1184. } else {
  1185. if (image) {
  1186. return i18next.t(
  1187. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},图片输入倍率 {{imageRatio}},{{ratioType}} {{ratio}}',
  1188. {
  1189. modelRatio: modelRatio,
  1190. cacheRatio: cacheRatio,
  1191. completionRatio: completionRatio,
  1192. imageRatio: imageRatio,
  1193. ratioType: ratioLabel,
  1194. ratio,
  1195. },
  1196. );
  1197. } else if (webSearch) {
  1198. return i18next.t(
  1199. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}},Web 搜索调用 {{webSearchCallCount}} 次',
  1200. {
  1201. modelRatio: modelRatio,
  1202. cacheRatio: cacheRatio,
  1203. completionRatio: completionRatio,
  1204. ratioType: ratioLabel,
  1205. ratio,
  1206. webSearchCallCount,
  1207. },
  1208. );
  1209. } else {
  1210. return i18next.t(
  1211. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}}',
  1212. {
  1213. modelRatio: modelRatio,
  1214. cacheRatio: cacheRatio,
  1215. completionRatio: completionRatio,
  1216. ratioType: ratioLabel,
  1217. ratio,
  1218. },
  1219. );
  1220. }
  1221. }
  1222. }
  1223. export function renderModelPriceSimple(
  1224. modelRatio,
  1225. modelPrice = -1,
  1226. groupRatio,
  1227. user_group_ratio,
  1228. cacheTokens = 0,
  1229. cacheRatio = 1.0,
  1230. cacheCreationTokens = 0,
  1231. cacheCreationRatio = 1.0,
  1232. image = false,
  1233. imageRatio = 1.0,
  1234. isSystemPromptOverride = false,
  1235. provider = 'openai',
  1236. ) {
  1237. return renderPriceSimpleCore({
  1238. modelRatio,
  1239. modelPrice,
  1240. groupRatio,
  1241. user_group_ratio,
  1242. cacheTokens,
  1243. cacheRatio,
  1244. cacheCreationTokens,
  1245. cacheCreationRatio,
  1246. image,
  1247. imageRatio,
  1248. isSystemPromptOverride,
  1249. });
  1250. }
  1251. export function renderAudioModelPrice(
  1252. inputTokens,
  1253. completionTokens,
  1254. modelRatio,
  1255. modelPrice = -1,
  1256. completionRatio,
  1257. audioInputTokens,
  1258. audioCompletionTokens,
  1259. audioRatio,
  1260. audioCompletionRatio,
  1261. groupRatio,
  1262. user_group_ratio,
  1263. cacheTokens = 0,
  1264. cacheRatio = 1.0,
  1265. ) {
  1266. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1267. groupRatio,
  1268. user_group_ratio,
  1269. );
  1270. groupRatio = effectiveGroupRatio;
  1271. // 1 ratio = $0.002 / 1K tokens
  1272. if (modelPrice !== -1) {
  1273. return i18next.t(
  1274. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  1275. {
  1276. price: modelPrice,
  1277. ratio: groupRatio,
  1278. total: modelPrice * groupRatio,
  1279. ratioType: ratioLabel,
  1280. },
  1281. );
  1282. } else {
  1283. if (completionRatio === undefined) {
  1284. completionRatio = 0;
  1285. }
  1286. // try toFixed audioRatio
  1287. audioRatio = parseFloat(audioRatio).toFixed(6);
  1288. // 这里的 *2 是因为 1倍率=0.002刀,请勿删除
  1289. let inputRatioPrice = modelRatio * 2.0;
  1290. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  1291. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  1292. // Calculate effective input tokens (non-cached + cached with ratio applied)
  1293. const effectiveInputTokens =
  1294. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  1295. let textPrice =
  1296. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1297. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1298. let audioPrice =
  1299. (audioInputTokens / 1000000) * inputRatioPrice * audioRatio * groupRatio +
  1300. (audioCompletionTokens / 1000000) *
  1301. inputRatioPrice *
  1302. audioRatio *
  1303. audioCompletionRatio *
  1304. groupRatio;
  1305. let price = textPrice + audioPrice;
  1306. return (
  1307. <>
  1308. <article>
  1309. <p>
  1310. {i18next.t('提示价格:${{price}} / 1M tokens', {
  1311. price: inputRatioPrice,
  1312. })}
  1313. </p>
  1314. <p>
  1315. {i18next.t(
  1316. '补全价格:${{price}} * {{completionRatio}} = ${{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1317. {
  1318. price: inputRatioPrice,
  1319. total: completionRatioPrice,
  1320. completionRatio: completionRatio,
  1321. },
  1322. )}
  1323. </p>
  1324. {cacheTokens > 0 && (
  1325. <p>
  1326. {i18next.t(
  1327. '缓存价格:${{price}} * {{cacheRatio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1328. {
  1329. price: inputRatioPrice,
  1330. total: inputRatioPrice * cacheRatio,
  1331. cacheRatio: cacheRatio,
  1332. },
  1333. )}
  1334. </p>
  1335. )}
  1336. <p>
  1337. {i18next.t(
  1338. '音频提示价格:${{price}} * {{audioRatio}} = ${{total}} / 1M tokens (音频倍率: {{audioRatio}})',
  1339. {
  1340. price: inputRatioPrice,
  1341. total: inputRatioPrice * audioRatio,
  1342. audioRatio: audioRatio,
  1343. },
  1344. )}
  1345. </p>
  1346. <p>
  1347. {i18next.t(
  1348. '音频补全价格:${{price}} * {{audioRatio}} * {{audioCompRatio}} = ${{total}} / 1M tokens (音频补全倍率: {{audioCompRatio}})',
  1349. {
  1350. price: inputRatioPrice,
  1351. total: inputRatioPrice * audioRatio * audioCompletionRatio,
  1352. audioRatio: audioRatio,
  1353. audioCompRatio: audioCompletionRatio,
  1354. },
  1355. )}
  1356. </p>
  1357. <p>
  1358. {cacheTokens > 0
  1359. ? i18next.t(
  1360. '文字提示 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}} + 文字补全 {{completion}} tokens / 1M tokens * ${{compPrice}} = ${{total}}',
  1361. {
  1362. nonCacheInput: inputTokens - cacheTokens,
  1363. cacheInput: cacheTokens,
  1364. cachePrice: inputRatioPrice * cacheRatio,
  1365. price: inputRatioPrice,
  1366. completion: completionTokens,
  1367. compPrice: completionRatioPrice,
  1368. total: textPrice.toFixed(6),
  1369. },
  1370. )
  1371. : i18next.t(
  1372. '文字提示 {{input}} tokens / 1M tokens * ${{price}} + 文字补全 {{completion}} tokens / 1M tokens * ${{compPrice}} = ${{total}}',
  1373. {
  1374. input: inputTokens,
  1375. price: inputRatioPrice,
  1376. completion: completionTokens,
  1377. compPrice: completionRatioPrice,
  1378. total: textPrice.toFixed(6),
  1379. },
  1380. )}
  1381. </p>
  1382. <p>
  1383. {i18next.t(
  1384. '音频提示 {{input}} tokens / 1M tokens * ${{audioInputPrice}} + 音频补全 {{completion}} tokens / 1M tokens * ${{audioCompPrice}} = ${{total}}',
  1385. {
  1386. input: audioInputTokens,
  1387. completion: audioCompletionTokens,
  1388. audioInputPrice: audioRatio * inputRatioPrice,
  1389. audioCompPrice:
  1390. audioRatio * audioCompletionRatio * inputRatioPrice,
  1391. total: audioPrice.toFixed(6),
  1392. },
  1393. )}
  1394. </p>
  1395. <p>
  1396. {i18next.t(
  1397. '总价:文字价格 {{textPrice}} + 音频价格 {{audioPrice}} = ${{total}}',
  1398. {
  1399. total: price.toFixed(6),
  1400. textPrice: textPrice.toFixed(6),
  1401. audioPrice: audioPrice.toFixed(6),
  1402. },
  1403. )}
  1404. </p>
  1405. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1406. </article>
  1407. </>
  1408. );
  1409. }
  1410. }
  1411. export function renderQuotaWithPrompt(quota, digits) {
  1412. let displayInCurrency = localStorage.getItem('display_in_currency');
  1413. displayInCurrency = displayInCurrency === 'true';
  1414. if (displayInCurrency) {
  1415. return i18next.t('等价金额:') + renderQuota(quota, digits);
  1416. }
  1417. return '';
  1418. }
  1419. export function renderClaudeModelPrice(
  1420. inputTokens,
  1421. completionTokens,
  1422. modelRatio,
  1423. modelPrice = -1,
  1424. completionRatio,
  1425. groupRatio,
  1426. user_group_ratio,
  1427. cacheTokens = 0,
  1428. cacheRatio = 1.0,
  1429. cacheCreationTokens = 0,
  1430. cacheCreationRatio = 1.0,
  1431. ) {
  1432. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1433. groupRatio,
  1434. user_group_ratio,
  1435. );
  1436. groupRatio = effectiveGroupRatio;
  1437. if (modelPrice !== -1) {
  1438. return i18next.t(
  1439. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  1440. {
  1441. price: modelPrice,
  1442. ratioType: ratioLabel,
  1443. ratio: groupRatio,
  1444. total: modelPrice * groupRatio,
  1445. },
  1446. );
  1447. } else {
  1448. if (completionRatio === undefined) {
  1449. completionRatio = 0;
  1450. }
  1451. const completionRatioValue = completionRatio || 0;
  1452. const inputRatioPrice = modelRatio * 2.0;
  1453. const completionRatioPrice = modelRatio * 2.0 * completionRatioValue;
  1454. let cacheRatioPrice = (modelRatio * 2.0 * cacheRatio).toFixed(2);
  1455. let cacheCreationRatioPrice = modelRatio * 2.0 * cacheCreationRatio;
  1456. // Calculate effective input tokens (non-cached + cached with ratio applied + cache creation with ratio applied)
  1457. const nonCachedTokens = inputTokens;
  1458. const effectiveInputTokens =
  1459. nonCachedTokens +
  1460. cacheTokens * cacheRatio +
  1461. cacheCreationTokens * cacheCreationRatio;
  1462. let price =
  1463. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1464. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1465. return (
  1466. <>
  1467. <article>
  1468. <p>
  1469. {i18next.t('提示价格:${{price}} / 1M tokens', {
  1470. price: inputRatioPrice,
  1471. })}
  1472. </p>
  1473. <p>
  1474. {i18next.t(
  1475. '补全价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens',
  1476. {
  1477. price: inputRatioPrice,
  1478. ratio: completionRatio,
  1479. total: completionRatioPrice,
  1480. },
  1481. )}
  1482. </p>
  1483. {cacheTokens > 0 && (
  1484. <p>
  1485. {i18next.t(
  1486. '缓存价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1487. {
  1488. price: inputRatioPrice,
  1489. ratio: cacheRatio,
  1490. total: cacheRatioPrice,
  1491. cacheRatio: cacheRatio,
  1492. },
  1493. )}
  1494. </p>
  1495. )}
  1496. {cacheCreationTokens > 0 && (
  1497. <p>
  1498. {i18next.t(
  1499. '缓存创建价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (缓存创建倍率: {{cacheCreationRatio}})',
  1500. {
  1501. price: inputRatioPrice,
  1502. ratio: cacheCreationRatio,
  1503. total: cacheCreationRatioPrice,
  1504. cacheCreationRatio: cacheCreationRatio,
  1505. },
  1506. )}
  1507. </p>
  1508. )}
  1509. <p></p>
  1510. <p>
  1511. {cacheTokens > 0 || cacheCreationTokens > 0
  1512. ? i18next.t(
  1513. '提示 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}} + 缓存创建 {{cacheCreationInput}} tokens / 1M tokens * ${{cacheCreationPrice}} + 补全 {{completion}} tokens / 1M tokens * ${{compPrice}} * {{ratioType}} {{ratio}} = ${{total}}',
  1514. {
  1515. nonCacheInput: nonCachedTokens,
  1516. cacheInput: cacheTokens,
  1517. cacheRatio: cacheRatio,
  1518. cacheCreationInput: cacheCreationTokens,
  1519. cacheCreationRatio: cacheCreationRatio,
  1520. cachePrice: cacheRatioPrice,
  1521. cacheCreationPrice: cacheCreationRatioPrice,
  1522. price: inputRatioPrice,
  1523. completion: completionTokens,
  1524. compPrice: completionRatioPrice,
  1525. ratio: groupRatio,
  1526. ratioType: ratioLabel,
  1527. total: price.toFixed(6),
  1528. },
  1529. )
  1530. : i18next.t(
  1531. '提示 {{input}} tokens / 1M tokens * ${{price}} + 补全 {{completion}} tokens / 1M tokens * ${{compPrice}} * {{ratioType}} {{ratio}} = ${{total}}',
  1532. {
  1533. input: inputTokens,
  1534. price: inputRatioPrice,
  1535. completion: completionTokens,
  1536. compPrice: completionRatioPrice,
  1537. ratio: groupRatio,
  1538. ratioType: ratioLabel,
  1539. total: price.toFixed(6),
  1540. },
  1541. )}
  1542. </p>
  1543. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1544. </article>
  1545. </>
  1546. );
  1547. }
  1548. }
  1549. export function renderClaudeLogContent(
  1550. modelRatio,
  1551. completionRatio,
  1552. modelPrice = -1,
  1553. groupRatio,
  1554. user_group_ratio,
  1555. cacheRatio = 1.0,
  1556. cacheCreationRatio = 1.0,
  1557. ) {
  1558. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1559. groupRatio,
  1560. user_group_ratio,
  1561. );
  1562. groupRatio = effectiveGroupRatio;
  1563. if (modelPrice !== -1) {
  1564. return i18next.t('模型价格 ${{price}},{{ratioType}} {{ratio}}', {
  1565. price: modelPrice,
  1566. ratioType: ratioLabel,
  1567. ratio: groupRatio,
  1568. });
  1569. } else {
  1570. return i18next.t(
  1571. '模型倍率 {{modelRatio}},输出倍率 {{completionRatio}},缓存倍率 {{cacheRatio}},缓存创建倍率 {{cacheCreationRatio}},{{ratioType}} {{ratio}}',
  1572. {
  1573. modelRatio: modelRatio,
  1574. completionRatio: completionRatio,
  1575. cacheRatio: cacheRatio,
  1576. cacheCreationRatio: cacheCreationRatio,
  1577. ratioType: ratioLabel,
  1578. ratio: groupRatio,
  1579. },
  1580. );
  1581. }
  1582. }
  1583. // 已统一至 renderModelPriceSimple,若仍有遗留引用,请改为传入 provider='claude'
  1584. /**
  1585. * rehype 插件:将段落等文本节点拆分为逐词 <span>,并添加淡入动画 class。
  1586. * 仅在流式渲染阶段使用,避免已渲染文字重复动画。
  1587. */
  1588. export function rehypeSplitWordsIntoSpans(options = {}) {
  1589. const { previousContentLength = 0 } = options;
  1590. return (tree) => {
  1591. let currentCharCount = 0; // 当前已处理的字符数
  1592. visit(tree, 'element', (node) => {
  1593. if (
  1594. ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'strong'].includes(
  1595. node.tagName,
  1596. ) &&
  1597. node.children
  1598. ) {
  1599. const newChildren = [];
  1600. node.children.forEach((child) => {
  1601. if (child.type === 'text') {
  1602. try {
  1603. // 使用 Intl.Segmenter 精准拆分中英文及标点
  1604. const segmenter = new Intl.Segmenter('zh', {
  1605. granularity: 'word',
  1606. });
  1607. const segments = segmenter.segment(child.value);
  1608. Array.from(segments)
  1609. .map((seg) => seg.segment)
  1610. .filter(Boolean)
  1611. .forEach((word) => {
  1612. const wordStartPos = currentCharCount;
  1613. const wordEndPos = currentCharCount + word.length;
  1614. // 判断这个词是否是新增的(在 previousContentLength 之后)
  1615. const isNewContent = wordStartPos >= previousContentLength;
  1616. newChildren.push({
  1617. type: 'element',
  1618. tagName: 'span',
  1619. properties: {
  1620. className: isNewContent ? ['animate-fade-in'] : [],
  1621. },
  1622. children: [{ type: 'text', value: word }],
  1623. });
  1624. currentCharCount = wordEndPos;
  1625. });
  1626. } catch (_) {
  1627. // Fallback:如果浏览器不支持 Segmenter
  1628. const textStartPos = currentCharCount;
  1629. const isNewContent = textStartPos >= previousContentLength;
  1630. if (isNewContent) {
  1631. // 新内容,添加动画
  1632. newChildren.push({
  1633. type: 'element',
  1634. tagName: 'span',
  1635. properties: {
  1636. className: ['animate-fade-in'],
  1637. },
  1638. children: [{ type: 'text', value: child.value }],
  1639. });
  1640. } else {
  1641. // 旧内容,不添加动画
  1642. newChildren.push(child);
  1643. }
  1644. currentCharCount += child.value.length;
  1645. }
  1646. } else {
  1647. newChildren.push(child);
  1648. }
  1649. });
  1650. node.children = newChildren;
  1651. }
  1652. });
  1653. };
  1654. }