render.jsx 70 KB

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