render.jsx 67 KB

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