render.jsx 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  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. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  773. num = num.toFixed(digits);
  774. if (quotaDisplayType === 'CNY') {
  775. return '¥' + num;
  776. } else if (quotaDisplayType === 'USD') {
  777. return '$' + num;
  778. } else if (quotaDisplayType === 'CUSTOM') {
  779. const statusStr = localStorage.getItem('status');
  780. let symbol = '¤';
  781. try {
  782. if (statusStr) {
  783. const s = JSON.parse(statusStr);
  784. symbol = s?.custom_currency_symbol || symbol;
  785. }
  786. } catch (e) {}
  787. return symbol + num;
  788. } else {
  789. return num;
  790. }
  791. }
  792. export function renderNumberWithPoint(num) {
  793. if (num === undefined) return '';
  794. num = num.toFixed(2);
  795. if (num >= 100000) {
  796. // Convert number to string to manipulate it
  797. let numStr = num.toString();
  798. // Find the position of the decimal point
  799. let decimalPointIndex = numStr.indexOf('.');
  800. let wholePart = numStr;
  801. let decimalPart = '';
  802. // If there is a decimal point, split the number into whole and decimal parts
  803. if (decimalPointIndex !== -1) {
  804. wholePart = numStr.slice(0, decimalPointIndex);
  805. decimalPart = numStr.slice(decimalPointIndex);
  806. }
  807. // Take the first two and last two digits of the whole number part
  808. let shortenedWholePart = wholePart.slice(0, 2) + '..' + wholePart.slice(-2);
  809. // Return the formatted number
  810. return shortenedWholePart + decimalPart;
  811. }
  812. // If the number is less than 100,000, return it unmodified
  813. return num;
  814. }
  815. export function getQuotaPerUnit() {
  816. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  817. quotaPerUnit = parseFloat(quotaPerUnit);
  818. return quotaPerUnit;
  819. }
  820. export function renderUnitWithQuota(quota) {
  821. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  822. quotaPerUnit = parseFloat(quotaPerUnit);
  823. quota = parseFloat(quota);
  824. return quotaPerUnit * quota;
  825. }
  826. export function getQuotaWithUnit(quota, digits = 6) {
  827. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  828. quotaPerUnit = parseFloat(quotaPerUnit);
  829. return (quota / quotaPerUnit).toFixed(digits);
  830. }
  831. export function renderQuotaWithAmount(amount) {
  832. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  833. if (quotaDisplayType === 'TOKENS') {
  834. return renderNumber(renderUnitWithQuota(amount));
  835. }
  836. if (quotaDisplayType === 'CNY') {
  837. return '¥' + amount;
  838. } else if (quotaDisplayType === 'CUSTOM') {
  839. const statusStr = localStorage.getItem('status');
  840. let symbol = '¤';
  841. try {
  842. if (statusStr) {
  843. const s = JSON.parse(statusStr);
  844. symbol = s?.custom_currency_symbol || symbol;
  845. }
  846. } catch (e) {}
  847. return symbol + amount;
  848. }
  849. return '$' + amount;
  850. }
  851. export function renderQuota(quota, digits = 2) {
  852. let quotaPerUnit = localStorage.getItem('quota_per_unit');
  853. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  854. quotaPerUnit = parseFloat(quotaPerUnit);
  855. if (quotaDisplayType === 'TOKENS') {
  856. return renderNumber(quota);
  857. }
  858. const resultUSD = quota / quotaPerUnit;
  859. let symbol = '$';
  860. let value = resultUSD;
  861. if (quotaDisplayType === 'CNY') {
  862. const statusStr = localStorage.getItem('status');
  863. let usdRate = 1;
  864. try {
  865. if (statusStr) {
  866. const s = JSON.parse(statusStr);
  867. usdRate = s?.usd_exchange_rate || 1;
  868. }
  869. } catch (e) {}
  870. value = resultUSD * usdRate;
  871. symbol = '¥';
  872. } else if (quotaDisplayType === 'CUSTOM') {
  873. const statusStr = localStorage.getItem('status');
  874. let symbolCustom = '¤';
  875. let rate = 1;
  876. try {
  877. if (statusStr) {
  878. const s = JSON.parse(statusStr);
  879. symbolCustom = s?.custom_currency_symbol || symbolCustom;
  880. rate = s?.custom_currency_exchange_rate || rate;
  881. }
  882. } catch (e) {}
  883. value = resultUSD * rate;
  884. symbol = symbolCustom;
  885. }
  886. const fixedResult = value.toFixed(digits);
  887. if (parseFloat(fixedResult) === 0 && quota > 0 && value > 0) {
  888. const minValue = Math.pow(10, -digits);
  889. return symbol + minValue.toFixed(digits);
  890. }
  891. return symbol + fixedResult;
  892. }
  893. function isValidGroupRatio(ratio) {
  894. return Number.isFinite(ratio) && ratio !== -1;
  895. }
  896. /**
  897. * Helper function to get effective ratio and label
  898. * @param {number} groupRatio - The default group ratio
  899. * @param {number} user_group_ratio - The user-specific group ratio
  900. * @returns {Object} - Object containing { ratio, label, useUserGroupRatio }
  901. */
  902. function getEffectiveRatio(groupRatio, user_group_ratio) {
  903. const useUserGroupRatio = isValidGroupRatio(user_group_ratio);
  904. const ratioLabel = useUserGroupRatio
  905. ? i18next.t('专属倍率')
  906. : i18next.t('分组倍率');
  907. const effectiveRatio = useUserGroupRatio ? user_group_ratio : groupRatio;
  908. return {
  909. ratio: effectiveRatio,
  910. label: ratioLabel,
  911. useUserGroupRatio: useUserGroupRatio,
  912. };
  913. }
  914. // Shared core for simple price rendering (used by OpenAI-like and Claude-like variants)
  915. function renderPriceSimpleCore({
  916. modelRatio,
  917. modelPrice = -1,
  918. groupRatio,
  919. user_group_ratio,
  920. cacheTokens = 0,
  921. cacheRatio = 1.0,
  922. cacheCreationTokens = 0,
  923. cacheCreationRatio = 1.0,
  924. image = false,
  925. imageRatio = 1.0,
  926. isSystemPromptOverride = false,
  927. }) {
  928. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  929. groupRatio,
  930. user_group_ratio,
  931. );
  932. const finalGroupRatio = effectiveGroupRatio;
  933. if (modelPrice !== -1) {
  934. return i18next.t('价格:${{price}} * {{ratioType}}:{{ratio}}', {
  935. price: modelPrice,
  936. ratioType: ratioLabel,
  937. ratio: finalGroupRatio,
  938. });
  939. }
  940. const parts = [];
  941. // base: model ratio
  942. parts.push(i18next.t('模型: {{ratio}}'));
  943. // cache part (label differs when with image)
  944. if (cacheTokens !== 0) {
  945. parts.push(i18next.t('缓存: {{cacheRatio}}'));
  946. }
  947. // cache creation part (Claude specific if passed)
  948. if (cacheCreationTokens !== 0) {
  949. parts.push(i18next.t('缓存创建: {{cacheCreationRatio}}'));
  950. }
  951. // image part
  952. if (image) {
  953. parts.push(i18next.t('图片输入: {{imageRatio}}'));
  954. }
  955. parts.push(`{{ratioType}}: {{groupRatio}}`);
  956. let result = i18next.t(parts.join(' * '), {
  957. ratio: modelRatio,
  958. ratioType: ratioLabel,
  959. groupRatio: finalGroupRatio,
  960. cacheRatio: cacheRatio,
  961. cacheCreationRatio: cacheCreationRatio,
  962. imageRatio: imageRatio,
  963. });
  964. if (isSystemPromptOverride) {
  965. result += '\n\r' + i18next.t('系统提示覆盖');
  966. }
  967. return result;
  968. }
  969. export function renderModelPrice(
  970. inputTokens,
  971. completionTokens,
  972. modelRatio,
  973. modelPrice = -1,
  974. completionRatio,
  975. groupRatio,
  976. user_group_ratio,
  977. cacheTokens = 0,
  978. cacheRatio = 1.0,
  979. image = false,
  980. imageRatio = 1.0,
  981. imageOutputTokens = 0,
  982. webSearch = false,
  983. webSearchCallCount = 0,
  984. webSearchPrice = 0,
  985. fileSearch = false,
  986. fileSearchCallCount = 0,
  987. fileSearchPrice = 0,
  988. audioInputSeperatePrice = false,
  989. audioInputTokens = 0,
  990. audioInputPrice = 0,
  991. imageGenerationCall = false,
  992. imageGenerationCallPrice = 0,
  993. ) {
  994. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  995. groupRatio,
  996. user_group_ratio,
  997. );
  998. groupRatio = effectiveGroupRatio;
  999. if (modelPrice !== -1) {
  1000. return i18next.t(
  1001. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  1002. {
  1003. price: modelPrice,
  1004. ratio: groupRatio,
  1005. total: modelPrice * groupRatio,
  1006. ratioType: ratioLabel,
  1007. },
  1008. );
  1009. } else {
  1010. if (completionRatio === undefined) {
  1011. completionRatio = 0;
  1012. }
  1013. let inputRatioPrice = modelRatio * 2.0;
  1014. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  1015. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  1016. let imageRatioPrice = modelRatio * 2.0 * imageRatio;
  1017. // Calculate effective input tokens (non-cached + cached with ratio applied)
  1018. let effectiveInputTokens =
  1019. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  1020. // Handle image tokens if present
  1021. if (image && imageOutputTokens > 0) {
  1022. effectiveInputTokens =
  1023. inputTokens - imageOutputTokens + imageOutputTokens * imageRatio;
  1024. }
  1025. if (audioInputTokens > 0) {
  1026. effectiveInputTokens -= audioInputTokens;
  1027. }
  1028. let price =
  1029. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1030. (audioInputTokens / 1000000) * audioInputPrice * groupRatio +
  1031. (completionTokens / 1000000) * completionRatioPrice * groupRatio +
  1032. (webSearchCallCount / 1000) * webSearchPrice * groupRatio +
  1033. (fileSearchCallCount / 1000) * fileSearchPrice * groupRatio +
  1034. imageGenerationCallPrice * groupRatio;
  1035. return (
  1036. <>
  1037. <article>
  1038. <p>
  1039. {i18next.t('输入价格:${{price}} / 1M tokens{{audioPrice}}', {
  1040. price: inputRatioPrice,
  1041. audioPrice: audioInputSeperatePrice
  1042. ? `,音频 $${audioInputPrice} / 1M tokens`
  1043. : '',
  1044. })}
  1045. </p>
  1046. <p>
  1047. {i18next.t(
  1048. '输出价格:${{price}} * {{completionRatio}} = ${{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1049. {
  1050. price: inputRatioPrice,
  1051. total: completionRatioPrice,
  1052. completionRatio: completionRatio,
  1053. },
  1054. )}
  1055. </p>
  1056. {cacheTokens > 0 && (
  1057. <p>
  1058. {i18next.t(
  1059. '缓存价格:${{price}} * {{cacheRatio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1060. {
  1061. price: inputRatioPrice,
  1062. total: inputRatioPrice * cacheRatio,
  1063. cacheRatio: cacheRatio,
  1064. },
  1065. )}
  1066. </p>
  1067. )}
  1068. {image && imageOutputTokens > 0 && (
  1069. <p>
  1070. {i18next.t(
  1071. '图片输入价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (图片倍率: {{imageRatio}})',
  1072. {
  1073. price: imageRatioPrice,
  1074. ratio: groupRatio,
  1075. total: imageRatioPrice * groupRatio,
  1076. imageRatio: imageRatio,
  1077. },
  1078. )}
  1079. </p>
  1080. )}
  1081. {webSearch && webSearchCallCount > 0 && (
  1082. <p>
  1083. {i18next.t('Web搜索价格:${{price}} / 1K 次', {
  1084. price: webSearchPrice,
  1085. })}
  1086. </p>
  1087. )}
  1088. {fileSearch && fileSearchCallCount > 0 && (
  1089. <p>
  1090. {i18next.t('文件搜索价格:${{price}} / 1K 次', {
  1091. price: fileSearchPrice,
  1092. })}
  1093. </p>
  1094. )}
  1095. {imageGenerationCall && imageGenerationCallPrice > 0 && (
  1096. <p>
  1097. {i18next.t('图片生成调用:${{price}} / 1次', {
  1098. price: imageGenerationCallPrice,
  1099. })}
  1100. </p>
  1101. )}
  1102. <p>
  1103. {(() => {
  1104. // 构建输入部分描述
  1105. let inputDesc = '';
  1106. if (image && imageOutputTokens > 0) {
  1107. inputDesc = i18next.t(
  1108. '(输入 {{nonImageInput}} tokens + 图片输入 {{imageInput}} tokens * {{imageRatio}} / 1M tokens * ${{price}}',
  1109. {
  1110. nonImageInput: inputTokens - imageOutputTokens,
  1111. imageInput: imageOutputTokens,
  1112. imageRatio: imageRatio,
  1113. price: inputRatioPrice,
  1114. },
  1115. );
  1116. } else if (cacheTokens > 0) {
  1117. inputDesc = i18next.t(
  1118. '(输入 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}}',
  1119. {
  1120. nonCacheInput: inputTokens - cacheTokens,
  1121. cacheInput: cacheTokens,
  1122. price: inputRatioPrice,
  1123. cachePrice: cacheRatioPrice,
  1124. },
  1125. );
  1126. } else if (audioInputSeperatePrice && audioInputTokens > 0) {
  1127. inputDesc = i18next.t(
  1128. '(输入 {{nonAudioInput}} tokens / 1M tokens * ${{price}} + 音频输入 {{audioInput}} tokens / 1M tokens * ${{audioPrice}}',
  1129. {
  1130. nonAudioInput: inputTokens - audioInputTokens,
  1131. audioInput: audioInputTokens,
  1132. price: inputRatioPrice,
  1133. audioPrice: audioInputPrice,
  1134. },
  1135. );
  1136. } else {
  1137. inputDesc = i18next.t(
  1138. '(输入 {{input}} tokens / 1M tokens * ${{price}}',
  1139. {
  1140. input: inputTokens,
  1141. price: inputRatioPrice,
  1142. },
  1143. );
  1144. }
  1145. // 构建输出部分描述
  1146. const outputDesc = i18next.t(
  1147. '输出 {{completion}} tokens / 1M tokens * ${{compPrice}}) * {{ratioType}} {{ratio}}',
  1148. {
  1149. completion: completionTokens,
  1150. compPrice: completionRatioPrice,
  1151. ratio: groupRatio,
  1152. ratioType: ratioLabel,
  1153. },
  1154. );
  1155. // 构建额外服务描述
  1156. const extraServices = [
  1157. webSearch && webSearchCallCount > 0
  1158. ? i18next.t(
  1159. ' + Web搜索 {{count}}次 / 1K 次 * ${{price}} * {{ratioType}} {{ratio}}',
  1160. {
  1161. count: webSearchCallCount,
  1162. price: webSearchPrice,
  1163. ratio: groupRatio,
  1164. ratioType: ratioLabel,
  1165. },
  1166. )
  1167. : '',
  1168. fileSearch && fileSearchCallCount > 0
  1169. ? i18next.t(
  1170. ' + 文件搜索 {{count}}次 / 1K 次 * ${{price}} * {{ratioType}} {{ratio}}',
  1171. {
  1172. count: fileSearchCallCount,
  1173. price: fileSearchPrice,
  1174. ratio: groupRatio,
  1175. ratioType: ratioLabel,
  1176. },
  1177. )
  1178. : '',
  1179. imageGenerationCall && imageGenerationCallPrice > 0
  1180. ? i18next.t(
  1181. ' + 图片生成调用 ${{price}} / 1次 * {{ratioType}} {{ratio}}',
  1182. {
  1183. price: imageGenerationCallPrice,
  1184. ratio: groupRatio,
  1185. ratioType: ratioLabel,
  1186. },
  1187. )
  1188. : '',
  1189. ].join('');
  1190. return i18next.t(
  1191. '{{inputDesc}} + {{outputDesc}}{{extraServices}} = ${{total}}',
  1192. {
  1193. inputDesc,
  1194. outputDesc,
  1195. extraServices,
  1196. total: price.toFixed(6),
  1197. },
  1198. );
  1199. })()}
  1200. </p>
  1201. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1202. </article>
  1203. </>
  1204. );
  1205. }
  1206. }
  1207. export function renderLogContent(
  1208. modelRatio,
  1209. completionRatio,
  1210. modelPrice = -1,
  1211. groupRatio,
  1212. user_group_ratio,
  1213. cacheRatio = 1.0,
  1214. image = false,
  1215. imageRatio = 1.0,
  1216. webSearch = false,
  1217. webSearchCallCount = 0,
  1218. fileSearch = false,
  1219. fileSearchCallCount = 0,
  1220. ) {
  1221. const {
  1222. ratio,
  1223. label: ratioLabel,
  1224. useUserGroupRatio: useUserGroupRatio,
  1225. } = getEffectiveRatio(groupRatio, user_group_ratio);
  1226. if (modelPrice !== -1) {
  1227. return i18next.t('模型价格 ${{price}},{{ratioType}} {{ratio}}', {
  1228. price: modelPrice,
  1229. ratioType: ratioLabel,
  1230. ratio,
  1231. });
  1232. } else {
  1233. if (image) {
  1234. return i18next.t(
  1235. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},图片输入倍率 {{imageRatio}},{{ratioType}} {{ratio}}',
  1236. {
  1237. modelRatio: modelRatio,
  1238. cacheRatio: cacheRatio,
  1239. completionRatio: completionRatio,
  1240. imageRatio: imageRatio,
  1241. ratioType: ratioLabel,
  1242. ratio,
  1243. },
  1244. );
  1245. } else if (webSearch) {
  1246. return i18next.t(
  1247. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}},Web 搜索调用 {{webSearchCallCount}} 次',
  1248. {
  1249. modelRatio: modelRatio,
  1250. cacheRatio: cacheRatio,
  1251. completionRatio: completionRatio,
  1252. ratioType: ratioLabel,
  1253. ratio,
  1254. webSearchCallCount,
  1255. },
  1256. );
  1257. } else {
  1258. return i18next.t(
  1259. '模型倍率 {{modelRatio}},缓存倍率 {{cacheRatio}},输出倍率 {{completionRatio}},{{ratioType}} {{ratio}}',
  1260. {
  1261. modelRatio: modelRatio,
  1262. cacheRatio: cacheRatio,
  1263. completionRatio: completionRatio,
  1264. ratioType: ratioLabel,
  1265. ratio,
  1266. },
  1267. );
  1268. }
  1269. }
  1270. }
  1271. export function renderModelPriceSimple(
  1272. modelRatio,
  1273. modelPrice = -1,
  1274. groupRatio,
  1275. user_group_ratio,
  1276. cacheTokens = 0,
  1277. cacheRatio = 1.0,
  1278. cacheCreationTokens = 0,
  1279. cacheCreationRatio = 1.0,
  1280. image = false,
  1281. imageRatio = 1.0,
  1282. isSystemPromptOverride = false,
  1283. provider = 'openai',
  1284. ) {
  1285. return renderPriceSimpleCore({
  1286. modelRatio,
  1287. modelPrice,
  1288. groupRatio,
  1289. user_group_ratio,
  1290. cacheTokens,
  1291. cacheRatio,
  1292. cacheCreationTokens,
  1293. cacheCreationRatio,
  1294. image,
  1295. imageRatio,
  1296. isSystemPromptOverride,
  1297. });
  1298. }
  1299. export function renderAudioModelPrice(
  1300. inputTokens,
  1301. completionTokens,
  1302. modelRatio,
  1303. modelPrice = -1,
  1304. completionRatio,
  1305. audioInputTokens,
  1306. audioCompletionTokens,
  1307. audioRatio,
  1308. audioCompletionRatio,
  1309. groupRatio,
  1310. user_group_ratio,
  1311. cacheTokens = 0,
  1312. cacheRatio = 1.0,
  1313. ) {
  1314. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1315. groupRatio,
  1316. user_group_ratio,
  1317. );
  1318. groupRatio = effectiveGroupRatio;
  1319. // 1 ratio = $0.002 / 1K tokens
  1320. if (modelPrice !== -1) {
  1321. return i18next.t(
  1322. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  1323. {
  1324. price: modelPrice,
  1325. ratio: groupRatio,
  1326. total: modelPrice * groupRatio,
  1327. ratioType: ratioLabel,
  1328. },
  1329. );
  1330. } else {
  1331. if (completionRatio === undefined) {
  1332. completionRatio = 0;
  1333. }
  1334. // try toFixed audioRatio
  1335. audioRatio = parseFloat(audioRatio).toFixed(6);
  1336. // 这里的 *2 是因为 1倍率=0.002刀,请勿删除
  1337. let inputRatioPrice = modelRatio * 2.0;
  1338. let completionRatioPrice = modelRatio * 2.0 * completionRatio;
  1339. let cacheRatioPrice = modelRatio * 2.0 * cacheRatio;
  1340. // Calculate effective input tokens (non-cached + cached with ratio applied)
  1341. const effectiveInputTokens =
  1342. inputTokens - cacheTokens + cacheTokens * cacheRatio;
  1343. let textPrice =
  1344. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1345. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1346. let audioPrice =
  1347. (audioInputTokens / 1000000) * inputRatioPrice * audioRatio * groupRatio +
  1348. (audioCompletionTokens / 1000000) *
  1349. inputRatioPrice *
  1350. audioRatio *
  1351. audioCompletionRatio *
  1352. groupRatio;
  1353. let price = textPrice + audioPrice;
  1354. return (
  1355. <>
  1356. <article>
  1357. <p>
  1358. {i18next.t('提示价格:${{price}} / 1M tokens', {
  1359. price: inputRatioPrice,
  1360. })}
  1361. </p>
  1362. <p>
  1363. {i18next.t(
  1364. '补全价格:${{price}} * {{completionRatio}} = ${{total}} / 1M tokens (补全倍率: {{completionRatio}})',
  1365. {
  1366. price: inputRatioPrice,
  1367. total: completionRatioPrice,
  1368. completionRatio: completionRatio,
  1369. },
  1370. )}
  1371. </p>
  1372. {cacheTokens > 0 && (
  1373. <p>
  1374. {i18next.t(
  1375. '缓存价格:${{price}} * {{cacheRatio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1376. {
  1377. price: inputRatioPrice,
  1378. total: inputRatioPrice * cacheRatio,
  1379. cacheRatio: cacheRatio,
  1380. },
  1381. )}
  1382. </p>
  1383. )}
  1384. <p>
  1385. {i18next.t(
  1386. '音频提示价格:${{price}} * {{audioRatio}} = ${{total}} / 1M tokens (音频倍率: {{audioRatio}})',
  1387. {
  1388. price: inputRatioPrice,
  1389. total: inputRatioPrice * audioRatio,
  1390. audioRatio: audioRatio,
  1391. },
  1392. )}
  1393. </p>
  1394. <p>
  1395. {i18next.t(
  1396. '音频补全价格:${{price}} * {{audioRatio}} * {{audioCompRatio}} = ${{total}} / 1M tokens (音频补全倍率: {{audioCompRatio}})',
  1397. {
  1398. price: inputRatioPrice,
  1399. total: inputRatioPrice * audioRatio * audioCompletionRatio,
  1400. audioRatio: audioRatio,
  1401. audioCompRatio: audioCompletionRatio,
  1402. },
  1403. )}
  1404. </p>
  1405. <p>
  1406. {cacheTokens > 0
  1407. ? i18next.t(
  1408. '文字提示 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}} + 文字补全 {{completion}} tokens / 1M tokens * ${{compPrice}} = ${{total}}',
  1409. {
  1410. nonCacheInput: inputTokens - cacheTokens,
  1411. cacheInput: cacheTokens,
  1412. cachePrice: inputRatioPrice * cacheRatio,
  1413. price: inputRatioPrice,
  1414. completion: completionTokens,
  1415. compPrice: completionRatioPrice,
  1416. total: textPrice.toFixed(6),
  1417. },
  1418. )
  1419. : i18next.t(
  1420. '文字提示 {{input}} tokens / 1M tokens * ${{price}} + 文字补全 {{completion}} tokens / 1M tokens * ${{compPrice}} = ${{total}}',
  1421. {
  1422. input: inputTokens,
  1423. price: inputRatioPrice,
  1424. completion: completionTokens,
  1425. compPrice: completionRatioPrice,
  1426. total: textPrice.toFixed(6),
  1427. },
  1428. )}
  1429. </p>
  1430. <p>
  1431. {i18next.t(
  1432. '音频提示 {{input}} tokens / 1M tokens * ${{audioInputPrice}} + 音频补全 {{completion}} tokens / 1M tokens * ${{audioCompPrice}} = ${{total}}',
  1433. {
  1434. input: audioInputTokens,
  1435. completion: audioCompletionTokens,
  1436. audioInputPrice: audioRatio * inputRatioPrice,
  1437. audioCompPrice:
  1438. audioRatio * audioCompletionRatio * inputRatioPrice,
  1439. total: audioPrice.toFixed(6),
  1440. },
  1441. )}
  1442. </p>
  1443. <p>
  1444. {i18next.t(
  1445. '总价:文字价格 {{textPrice}} + 音频价格 {{audioPrice}} = ${{total}}',
  1446. {
  1447. total: price.toFixed(6),
  1448. textPrice: textPrice.toFixed(6),
  1449. audioPrice: audioPrice.toFixed(6),
  1450. },
  1451. )}
  1452. </p>
  1453. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1454. </article>
  1455. </>
  1456. );
  1457. }
  1458. }
  1459. export function renderQuotaWithPrompt(quota, digits) {
  1460. const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
  1461. if (quotaDisplayType !== 'TOKENS') {
  1462. return i18next.t('等价金额:') + renderQuota(quota, digits);
  1463. }
  1464. return '';
  1465. }
  1466. export function renderClaudeModelPrice(
  1467. inputTokens,
  1468. completionTokens,
  1469. modelRatio,
  1470. modelPrice = -1,
  1471. completionRatio,
  1472. groupRatio,
  1473. user_group_ratio,
  1474. cacheTokens = 0,
  1475. cacheRatio = 1.0,
  1476. cacheCreationTokens = 0,
  1477. cacheCreationRatio = 1.0,
  1478. ) {
  1479. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1480. groupRatio,
  1481. user_group_ratio,
  1482. );
  1483. groupRatio = effectiveGroupRatio;
  1484. if (modelPrice !== -1) {
  1485. return i18next.t(
  1486. '模型价格:${{price}} * {{ratioType}}:{{ratio}} = ${{total}}',
  1487. {
  1488. price: modelPrice,
  1489. ratioType: ratioLabel,
  1490. ratio: groupRatio,
  1491. total: modelPrice * groupRatio,
  1492. },
  1493. );
  1494. } else {
  1495. if (completionRatio === undefined) {
  1496. completionRatio = 0;
  1497. }
  1498. const completionRatioValue = completionRatio || 0;
  1499. const inputRatioPrice = modelRatio * 2.0;
  1500. const completionRatioPrice = modelRatio * 2.0 * completionRatioValue;
  1501. let cacheRatioPrice = (modelRatio * 2.0 * cacheRatio).toFixed(2);
  1502. let cacheCreationRatioPrice = modelRatio * 2.0 * cacheCreationRatio;
  1503. // Calculate effective input tokens (non-cached + cached with ratio applied + cache creation with ratio applied)
  1504. const nonCachedTokens = inputTokens;
  1505. const effectiveInputTokens =
  1506. nonCachedTokens +
  1507. cacheTokens * cacheRatio +
  1508. cacheCreationTokens * cacheCreationRatio;
  1509. let price =
  1510. (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio +
  1511. (completionTokens / 1000000) * completionRatioPrice * groupRatio;
  1512. return (
  1513. <>
  1514. <article>
  1515. <p>
  1516. {i18next.t('提示价格:${{price}} / 1M tokens', {
  1517. price: inputRatioPrice,
  1518. })}
  1519. </p>
  1520. <p>
  1521. {i18next.t(
  1522. '补全价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens',
  1523. {
  1524. price: inputRatioPrice,
  1525. ratio: completionRatio,
  1526. total: completionRatioPrice,
  1527. },
  1528. )}
  1529. </p>
  1530. {cacheTokens > 0 && (
  1531. <p>
  1532. {i18next.t(
  1533. '缓存价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (缓存倍率: {{cacheRatio}})',
  1534. {
  1535. price: inputRatioPrice,
  1536. ratio: cacheRatio,
  1537. total: cacheRatioPrice,
  1538. cacheRatio: cacheRatio,
  1539. },
  1540. )}
  1541. </p>
  1542. )}
  1543. {cacheCreationTokens > 0 && (
  1544. <p>
  1545. {i18next.t(
  1546. '缓存创建价格:${{price}} * {{ratio}} = ${{total}} / 1M tokens (缓存创建倍率: {{cacheCreationRatio}})',
  1547. {
  1548. price: inputRatioPrice,
  1549. ratio: cacheCreationRatio,
  1550. total: cacheCreationRatioPrice,
  1551. cacheCreationRatio: cacheCreationRatio,
  1552. },
  1553. )}
  1554. </p>
  1555. )}
  1556. <p></p>
  1557. <p>
  1558. {cacheTokens > 0 || cacheCreationTokens > 0
  1559. ? i18next.t(
  1560. '提示 {{nonCacheInput}} tokens / 1M tokens * ${{price}} + 缓存 {{cacheInput}} tokens / 1M tokens * ${{cachePrice}} + 缓存创建 {{cacheCreationInput}} tokens / 1M tokens * ${{cacheCreationPrice}} + 补全 {{completion}} tokens / 1M tokens * ${{compPrice}} * {{ratioType}} {{ratio}} = ${{total}}',
  1561. {
  1562. nonCacheInput: nonCachedTokens,
  1563. cacheInput: cacheTokens,
  1564. cacheRatio: cacheRatio,
  1565. cacheCreationInput: cacheCreationTokens,
  1566. cacheCreationRatio: cacheCreationRatio,
  1567. cachePrice: cacheRatioPrice,
  1568. cacheCreationPrice: cacheCreationRatioPrice,
  1569. price: inputRatioPrice,
  1570. completion: completionTokens,
  1571. compPrice: completionRatioPrice,
  1572. ratio: groupRatio,
  1573. ratioType: ratioLabel,
  1574. total: price.toFixed(6),
  1575. },
  1576. )
  1577. : i18next.t(
  1578. '提示 {{input}} tokens / 1M tokens * ${{price}} + 补全 {{completion}} tokens / 1M tokens * ${{compPrice}} * {{ratioType}} {{ratio}} = ${{total}}',
  1579. {
  1580. input: inputTokens,
  1581. price: inputRatioPrice,
  1582. completion: completionTokens,
  1583. compPrice: completionRatioPrice,
  1584. ratio: groupRatio,
  1585. ratioType: ratioLabel,
  1586. total: price.toFixed(6),
  1587. },
  1588. )}
  1589. </p>
  1590. <p>{i18next.t('仅供参考,以实际扣费为准')}</p>
  1591. </article>
  1592. </>
  1593. );
  1594. }
  1595. }
  1596. export function renderClaudeLogContent(
  1597. modelRatio,
  1598. completionRatio,
  1599. modelPrice = -1,
  1600. groupRatio,
  1601. user_group_ratio,
  1602. cacheRatio = 1.0,
  1603. cacheCreationRatio = 1.0,
  1604. ) {
  1605. const { ratio: effectiveGroupRatio, label: ratioLabel } = getEffectiveRatio(
  1606. groupRatio,
  1607. user_group_ratio,
  1608. );
  1609. groupRatio = effectiveGroupRatio;
  1610. if (modelPrice !== -1) {
  1611. return i18next.t('模型价格 ${{price}},{{ratioType}} {{ratio}}', {
  1612. price: modelPrice,
  1613. ratioType: ratioLabel,
  1614. ratio: groupRatio,
  1615. });
  1616. } else {
  1617. return i18next.t(
  1618. '模型倍率 {{modelRatio}},输出倍率 {{completionRatio}},缓存倍率 {{cacheRatio}},缓存创建倍率 {{cacheCreationRatio}},{{ratioType}} {{ratio}}',
  1619. {
  1620. modelRatio: modelRatio,
  1621. completionRatio: completionRatio,
  1622. cacheRatio: cacheRatio,
  1623. cacheCreationRatio: cacheCreationRatio,
  1624. ratioType: ratioLabel,
  1625. ratio: groupRatio,
  1626. },
  1627. );
  1628. }
  1629. }
  1630. // 已统一至 renderModelPriceSimple,若仍有遗留引用,请改为传入 provider='claude'
  1631. /**
  1632. * rehype 插件:将段落等文本节点拆分为逐词 <span>,并添加淡入动画 class。
  1633. * 仅在流式渲染阶段使用,避免已渲染文字重复动画。
  1634. */
  1635. export function rehypeSplitWordsIntoSpans(options = {}) {
  1636. const { previousContentLength = 0 } = options;
  1637. return (tree) => {
  1638. let currentCharCount = 0; // 当前已处理的字符数
  1639. visit(tree, 'element', (node) => {
  1640. if (
  1641. ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'strong'].includes(
  1642. node.tagName,
  1643. ) &&
  1644. node.children
  1645. ) {
  1646. const newChildren = [];
  1647. node.children.forEach((child) => {
  1648. if (child.type === 'text') {
  1649. try {
  1650. // 使用 Intl.Segmenter 精准拆分中英文及标点
  1651. const segmenter = new Intl.Segmenter('zh', {
  1652. granularity: 'word',
  1653. });
  1654. const segments = segmenter.segment(child.value);
  1655. Array.from(segments)
  1656. .map((seg) => seg.segment)
  1657. .filter(Boolean)
  1658. .forEach((word) => {
  1659. const wordStartPos = currentCharCount;
  1660. const wordEndPos = currentCharCount + word.length;
  1661. // 判断这个词是否是新增的(在 previousContentLength 之后)
  1662. const isNewContent = wordStartPos >= previousContentLength;
  1663. newChildren.push({
  1664. type: 'element',
  1665. tagName: 'span',
  1666. properties: {
  1667. className: isNewContent ? ['animate-fade-in'] : [],
  1668. },
  1669. children: [{ type: 'text', value: word }],
  1670. });
  1671. currentCharCount = wordEndPos;
  1672. });
  1673. } catch (_) {
  1674. // Fallback:如果浏览器不支持 Segmenter
  1675. const textStartPos = currentCharCount;
  1676. const isNewContent = textStartPos >= previousContentLength;
  1677. if (isNewContent) {
  1678. // 新内容,添加动画
  1679. newChildren.push({
  1680. type: 'element',
  1681. tagName: 'span',
  1682. properties: {
  1683. className: ['animate-fade-in'],
  1684. },
  1685. children: [{ type: 'text', value: child.value }],
  1686. });
  1687. } else {
  1688. // 旧内容,不添加动画
  1689. newChildren.push(child);
  1690. }
  1691. currentCharCount += child.value.length;
  1692. }
  1693. } else {
  1694. newChildren.push(child);
  1695. }
  1696. });
  1697. node.children = newChildren;
  1698. }
  1699. });
  1700. };
  1701. }