ModelPricing.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. import React, { useContext, useEffect, useRef, useMemo, useState } from 'react';
  2. import { API, copy, showError, showInfo, showSuccess } from '../helpers';
  3. import { useTranslation } from 'react-i18next';
  4. import {
  5. Input,
  6. Layout,
  7. Modal,
  8. Space,
  9. Table,
  10. Tag,
  11. Tooltip,
  12. Popover,
  13. ImagePreview,
  14. Button,
  15. Card,
  16. Tabs,
  17. TabPane,
  18. Dropdown,
  19. } from '@douyinfe/semi-ui';
  20. import {
  21. IconVerify,
  22. IconHelpCircle,
  23. IconSearch,
  24. IconCopy,
  25. IconInfoCircle,
  26. } from '@douyinfe/semi-icons';
  27. import { UserContext } from '../context/User/index.js';
  28. import { Settings, AlertCircle } from 'lucide-react';
  29. import { MODEL_CATEGORIES } from '../constants';
  30. const ModelPricing = () => {
  31. const { t } = useTranslation();
  32. const [filteredValue, setFilteredValue] = useState([]);
  33. const compositionRef = useRef({ isComposition: false });
  34. const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  35. const [modalImageUrl, setModalImageUrl] = useState('');
  36. const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  37. const [selectedGroup, setSelectedGroup] = useState('default');
  38. const [activeKey, setActiveKey] = useState('all');
  39. const [pageSize, setPageSize] = useState(10);
  40. const rowSelection = useMemo(
  41. () => ({
  42. onChange: (selectedRowKeys, selectedRows) => {
  43. setSelectedRowKeys(selectedRowKeys);
  44. },
  45. }),
  46. [],
  47. );
  48. const handleChange = (value) => {
  49. if (compositionRef.current.isComposition) {
  50. return;
  51. }
  52. const newFilteredValue = value ? [value] : [];
  53. setFilteredValue(newFilteredValue);
  54. };
  55. const handleCompositionStart = () => {
  56. compositionRef.current.isComposition = true;
  57. };
  58. const handleCompositionEnd = (event) => {
  59. compositionRef.current.isComposition = false;
  60. const value = event.target.value;
  61. const newFilteredValue = value ? [value] : [];
  62. setFilteredValue(newFilteredValue);
  63. };
  64. function renderQuotaType(type) {
  65. switch (type) {
  66. case 1:
  67. return (
  68. <Tag color='teal' size='large' shape='circle'>
  69. {t('按次计费')}
  70. </Tag>
  71. );
  72. case 0:
  73. return (
  74. <Tag color='violet' size='large' shape='circle'>
  75. {t('按量计费')}
  76. </Tag>
  77. );
  78. default:
  79. return t('未知');
  80. }
  81. }
  82. function renderAvailable(available) {
  83. return available ? (
  84. <Popover
  85. content={
  86. <div style={{ padding: 8 }}>{t('您的分组可以使用该模型')}</div>
  87. }
  88. position='top'
  89. key={available}
  90. className="bg-green-50"
  91. >
  92. <IconVerify style={{ color: 'rgb(22 163 74)' }} size='large' />
  93. </Popover>
  94. ) : null;
  95. }
  96. const columns = [
  97. {
  98. title: t('可用性'),
  99. dataIndex: 'available',
  100. render: (text, record, index) => {
  101. return renderAvailable(record.enable_groups.includes(selectedGroup));
  102. },
  103. sorter: (a, b) => {
  104. const aAvailable = a.enable_groups.includes(selectedGroup);
  105. const bAvailable = b.enable_groups.includes(selectedGroup);
  106. return Number(aAvailable) - Number(bAvailable);
  107. },
  108. defaultSortOrder: 'descend',
  109. width: 100,
  110. },
  111. {
  112. title: t('模型名称'),
  113. dataIndex: 'model_name',
  114. render: (text, record, index) => {
  115. return (
  116. <Tag
  117. color='green'
  118. size='large'
  119. shape='circle'
  120. onClick={() => {
  121. copyText(text);
  122. }}
  123. >
  124. {text}
  125. </Tag>
  126. );
  127. },
  128. onFilter: (value, record) =>
  129. record.model_name.toLowerCase().includes(value.toLowerCase()),
  130. filteredValue,
  131. width: 200,
  132. },
  133. {
  134. title: t('计费类型'),
  135. dataIndex: 'quota_type',
  136. render: (text, record, index) => {
  137. return renderQuotaType(parseInt(text));
  138. },
  139. sorter: (a, b) => a.quota_type - b.quota_type,
  140. width: 120,
  141. },
  142. {
  143. title: t('可用分组'),
  144. dataIndex: 'enable_groups',
  145. render: (text, record, index) => {
  146. return (
  147. <Space wrap>
  148. {text.map((group) => {
  149. if (usableGroup[group]) {
  150. if (group === selectedGroup) {
  151. return (
  152. <Tag color='blue' size='large' shape='circle' prefixIcon={<IconVerify />}>
  153. {group}
  154. </Tag>
  155. );
  156. } else {
  157. return (
  158. <Tag
  159. color='blue'
  160. size='large'
  161. onClick={() => {
  162. setSelectedGroup(group);
  163. showInfo(
  164. t('当前查看的分组为:{{group}},倍率为:{{ratio}}', {
  165. group: group,
  166. ratio: groupRatio[group],
  167. }),
  168. );
  169. }}
  170. className="cursor-pointer hover:opacity-80 transition-opacity !rounded-full"
  171. >
  172. {group}
  173. </Tag>
  174. );
  175. }
  176. }
  177. })}
  178. </Space>
  179. );
  180. },
  181. },
  182. {
  183. title: () => (
  184. <div className="flex items-center space-x-1">
  185. <span>{t('倍率')}</span>
  186. <Tooltip content={t('倍率是为了方便换算不同价格的模型')}>
  187. <IconHelpCircle
  188. className="text-blue-500 cursor-pointer"
  189. onClick={() => {
  190. setModalImageUrl('/ratio.png');
  191. setIsModalOpenurl(true);
  192. }}
  193. />
  194. </Tooltip>
  195. </div>
  196. ),
  197. dataIndex: 'model_ratio',
  198. render: (text, record, index) => {
  199. let content = text;
  200. let completionRatio = parseFloat(record.completion_ratio.toFixed(3));
  201. content = (
  202. <div className="space-y-1">
  203. <div className="text-gray-700">
  204. {t('模型倍率')}:{record.quota_type === 0 ? text : t('无')}
  205. </div>
  206. <div className="text-gray-700">
  207. {t('补全倍率')}:
  208. {record.quota_type === 0 ? completionRatio : t('无')}
  209. </div>
  210. <div className="text-gray-700">
  211. {t('分组倍率')}:{groupRatio[selectedGroup]}
  212. </div>
  213. </div>
  214. );
  215. return content;
  216. },
  217. width: 200,
  218. },
  219. {
  220. title: t('模型价格'),
  221. dataIndex: 'model_price',
  222. render: (text, record, index) => {
  223. let content = text;
  224. if (record.quota_type === 0) {
  225. let inputRatioPrice =
  226. record.model_ratio * 2 * groupRatio[selectedGroup];
  227. let completionRatioPrice =
  228. record.model_ratio *
  229. record.completion_ratio *
  230. 2 *
  231. groupRatio[selectedGroup];
  232. content = (
  233. <div className="space-y-1">
  234. <div className="text-gray-700">
  235. {t('提示')} ${inputRatioPrice.toFixed(3)} / 1M tokens
  236. </div>
  237. <div className="text-gray-700">
  238. {t('补全')} ${completionRatioPrice.toFixed(3)} / 1M tokens
  239. </div>
  240. </div>
  241. );
  242. } else {
  243. let price = parseFloat(text) * groupRatio[selectedGroup];
  244. content = (
  245. <div className="text-gray-700">
  246. ${t('模型价格')}:${price.toFixed(3)}
  247. </div>
  248. );
  249. }
  250. return content;
  251. },
  252. width: 250,
  253. },
  254. ];
  255. const [models, setModels] = useState([]);
  256. const [loading, setLoading] = useState(true);
  257. const [userState, userDispatch] = useContext(UserContext);
  258. const [groupRatio, setGroupRatio] = useState({});
  259. const [usableGroup, setUsableGroup] = useState({});
  260. const setModelsFormat = (models, groupRatio) => {
  261. for (let i = 0; i < models.length; i++) {
  262. models[i].key = models[i].model_name;
  263. models[i].group_ratio = groupRatio[models[i].model_name];
  264. }
  265. models.sort((a, b) => {
  266. return a.quota_type - b.quota_type;
  267. });
  268. models.sort((a, b) => {
  269. if (a.model_name.startsWith('gpt') && !b.model_name.startsWith('gpt')) {
  270. return -1;
  271. } else if (
  272. !a.model_name.startsWith('gpt') &&
  273. b.model_name.startsWith('gpt')
  274. ) {
  275. return 1;
  276. } else {
  277. return a.model_name.localeCompare(b.model_name);
  278. }
  279. });
  280. setModels(models);
  281. };
  282. const loadPricing = async () => {
  283. setLoading(true);
  284. let url = '/api/pricing';
  285. const res = await API.get(url);
  286. const { success, message, data, group_ratio, usable_group } = res.data;
  287. if (success) {
  288. setGroupRatio(group_ratio);
  289. setUsableGroup(usable_group);
  290. setSelectedGroup(userState.user ? userState.user.group : 'default');
  291. setModelsFormat(data, group_ratio);
  292. } else {
  293. showError(message);
  294. }
  295. setLoading(false);
  296. };
  297. const refresh = async () => {
  298. await loadPricing();
  299. };
  300. const copyText = async (text) => {
  301. if (await copy(text)) {
  302. showSuccess(t('已复制:') + text);
  303. } else {
  304. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  305. }
  306. };
  307. useEffect(() => {
  308. refresh().then();
  309. }, []);
  310. const modelCategories = MODEL_CATEGORIES(t);
  311. const renderArrow = (items, pos, handleArrowClick) => {
  312. const style = {
  313. width: 32,
  314. height: 32,
  315. margin: '0 12px',
  316. display: 'flex',
  317. justifyContent: 'center',
  318. alignItems: 'center',
  319. borderRadius: '100%',
  320. background: 'rgba(var(--semi-grey-1), 1)',
  321. color: 'var(--semi-color-text)',
  322. cursor: 'pointer',
  323. };
  324. return (
  325. <Dropdown
  326. render={
  327. <Dropdown.Menu>
  328. {items.map(item => (
  329. <Dropdown.Item
  330. key={item.itemKey}
  331. onClick={() => setActiveKey(item.itemKey)}
  332. icon={modelCategories[item.itemKey]?.icon}
  333. >
  334. {modelCategories[item.itemKey]?.label || item.itemKey}
  335. </Dropdown.Item>
  336. ))}
  337. </Dropdown.Menu>
  338. }
  339. >
  340. <div style={style} onClick={handleArrowClick}>
  341. {pos === 'start' ? '←' : '→'}
  342. </div>
  343. </Dropdown>
  344. );
  345. };
  346. // 检查分类是否有对应的模型
  347. const availableCategories = useMemo(() => {
  348. if (!models.length) return ['all'];
  349. return Object.entries(modelCategories).filter(([key, category]) => {
  350. if (key === 'all') return true;
  351. return models.some(model => category.filter(model));
  352. }).map(([key]) => key);
  353. }, [models]);
  354. // 渲染标签页
  355. const renderTabs = () => {
  356. return (
  357. <Tabs
  358. renderArrow={renderArrow}
  359. activeKey={activeKey}
  360. type="card"
  361. collapsible
  362. onChange={key => setActiveKey(key)}
  363. >
  364. {Object.entries(modelCategories)
  365. .filter(([key]) => availableCategories.includes(key))
  366. .map(([key, category]) => (
  367. <TabPane
  368. tab={
  369. <span className="flex items-center gap-2">
  370. {category.icon && <span className="w-4 h-4">{category.icon}</span>}
  371. {category.label}
  372. </span>
  373. }
  374. itemKey={key}
  375. key={key}
  376. />
  377. ))}
  378. </Tabs>
  379. );
  380. };
  381. // 优化过滤逻辑
  382. const filteredModels = useMemo(() => {
  383. let result = models;
  384. // 先按分类过滤
  385. if (activeKey !== 'all') {
  386. result = result.filter(model => modelCategories[activeKey].filter(model));
  387. }
  388. // 再按搜索词过滤
  389. if (filteredValue.length > 0) {
  390. const searchTerm = filteredValue[0].toLowerCase();
  391. result = result.filter(model =>
  392. model.model_name.toLowerCase().includes(searchTerm)
  393. );
  394. }
  395. return result;
  396. }, [activeKey, models, filteredValue]);
  397. // 搜索和操作区组件
  398. const SearchAndActions = useMemo(() => (
  399. <Card className="!rounded-xl mb-6" shadows='hover'>
  400. <div className="flex flex-wrap items-center gap-4">
  401. <div className="flex-1 min-w-[200px]">
  402. <Input
  403. prefix={<IconSearch />}
  404. placeholder={t('模糊搜索模型名称')}
  405. className="!rounded-lg"
  406. onCompositionStart={handleCompositionStart}
  407. onCompositionEnd={handleCompositionEnd}
  408. onChange={handleChange}
  409. showClear
  410. size="large"
  411. />
  412. </div>
  413. <Button
  414. theme='light'
  415. type='primary'
  416. icon={<IconCopy />}
  417. onClick={() => copyText(selectedRowKeys)}
  418. disabled={selectedRowKeys.length === 0}
  419. className="!rounded-lg !bg-blue-500 hover:!bg-blue-600 text-white"
  420. size="large"
  421. >
  422. {t('复制选中模型')}
  423. </Button>
  424. </div>
  425. </Card>
  426. ), [selectedRowKeys, t]);
  427. // 表格组件
  428. const ModelTable = useMemo(() => (
  429. <Card className="!rounded-xl overflow-hidden" shadows='hover'>
  430. <Table
  431. columns={columns}
  432. dataSource={filteredModels}
  433. loading={loading}
  434. rowSelection={rowSelection}
  435. className="custom-table"
  436. pagination={{
  437. defaultPageSize: 10,
  438. pageSize: pageSize,
  439. showSizeChanger: true,
  440. pageSizeOptions: [10, 20, 50, 100],
  441. formatPageText: (page) =>
  442. t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
  443. start: page.currentStart,
  444. end: page.currentEnd,
  445. total: filteredModels.length,
  446. }),
  447. onPageSizeChange: (size) => setPageSize(size),
  448. }}
  449. />
  450. </Card>
  451. ), [filteredModels, loading, columns, rowSelection, pageSize, t]);
  452. return (
  453. <div className="min-h-screen bg-gray-50">
  454. <Layout>
  455. <Layout.Content>
  456. <div className="flex justify-center p-4 sm:p-6 md:p-8">
  457. <div className="w-full">
  458. {/* 主卡片容器 */}
  459. <Card className="!rounded-2xl shadow-lg border-0">
  460. {/* 顶部状态卡片 */}
  461. <Card
  462. className="!rounded-2xl !border-0 !shadow-2xl overflow-hidden mb-6"
  463. style={{
  464. background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 25%, #a855f7 50%, #c084fc 75%, #d8b4fe 100%)',
  465. position: 'relative'
  466. }}
  467. bodyStyle={{ padding: 0 }}
  468. >
  469. {/* 装饰性背景元素 */}
  470. <div className="absolute inset-0 overflow-hidden">
  471. <div className="absolute -top-10 -right-10 w-40 h-40 bg-white opacity-5 rounded-full"></div>
  472. <div className="absolute -bottom-16 -left-16 w-48 h-48 bg-white opacity-3 rounded-full"></div>
  473. <div className="absolute top-1/2 right-1/4 w-24 h-24 bg-yellow-400 opacity-10 rounded-full"></div>
  474. </div>
  475. <div className="relative p-6 sm:p-8" style={{ color: 'white' }}>
  476. <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4 lg:gap-6">
  477. <div className="flex items-start">
  478. <div className="w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-white/10 flex items-center justify-center mr-3 sm:mr-4">
  479. <Settings size={20} className="text-white" />
  480. </div>
  481. <div className="flex-1 min-w-0">
  482. <div className="text-base sm:text-lg font-semibold mb-1 sm:mb-2">
  483. {t('模型定价')}
  484. </div>
  485. <div className="text-sm text-white/80">
  486. {userState.user ? (
  487. <div className="flex items-center">
  488. <IconVerify className="mr-1.5 flex-shrink-0" size="small" />
  489. <span className="truncate">
  490. {t('当前分组')}: {userState.user.group},{t('倍率')}: {groupRatio[userState.user.group]}
  491. </span>
  492. </div>
  493. ) : (
  494. <div className="flex items-center">
  495. <AlertCircle size={14} className="mr-1.5 flex-shrink-0" />
  496. <span className="truncate">
  497. {t('未登录,使用默认分组倍率')}: {groupRatio['default']}
  498. </span>
  499. </div>
  500. )}
  501. </div>
  502. </div>
  503. </div>
  504. <div className="grid grid-cols-3 gap-2 sm:gap-3 mt-2 lg:mt-0">
  505. <div
  506. className="text-center px-2 py-2 sm:px-3 sm:py-2.5 bg-white/10 rounded-lg backdrop-blur-sm hover:bg-white/20 transition-colors duration-200"
  507. style={{ backdropFilter: 'blur(10px)' }}
  508. >
  509. <div className="text-xs text-white/70 mb-0.5">{t('分组倍率')}</div>
  510. <div className="text-sm sm:text-base font-semibold">{groupRatio[selectedGroup] || '1.0'}x</div>
  511. </div>
  512. <div
  513. className="text-center px-2 py-2 sm:px-3 sm:py-2.5 bg-white/10 rounded-lg backdrop-blur-sm hover:bg-white/20 transition-colors duration-200"
  514. style={{ backdropFilter: 'blur(10px)' }}
  515. >
  516. <div className="text-xs text-white/70 mb-0.5">{t('可用模型')}</div>
  517. <div className="text-sm sm:text-base font-semibold">
  518. {models.filter(m => m.enable_groups.includes(selectedGroup)).length}
  519. </div>
  520. </div>
  521. <div
  522. className="text-center px-2 py-2 sm:px-3 sm:py-2.5 bg-white/10 rounded-lg backdrop-blur-sm hover:bg-white/20 transition-colors duration-200"
  523. style={{ backdropFilter: 'blur(10px)' }}
  524. >
  525. <div className="text-xs text-white/70 mb-0.5">{t('计费类型')}</div>
  526. <div className="text-sm sm:text-base font-semibold">2</div>
  527. </div>
  528. </div>
  529. </div>
  530. {/* 计费说明 */}
  531. <div className="mt-4 sm:mt-5">
  532. <div className="flex items-start">
  533. <div
  534. className="w-full flex items-start space-x-2 px-3 py-2 sm:px-4 sm:py-2.5 rounded-lg text-xs sm:text-sm"
  535. style={{
  536. backgroundColor: 'rgba(255, 255, 255, 0.2)',
  537. color: 'white',
  538. backdropFilter: 'blur(10px)'
  539. }}
  540. >
  541. <IconInfoCircle className="flex-shrink-0 mt-0.5" size="small" />
  542. <span>
  543. {t('按量计费费用 = 分组倍率 × 模型倍率 × (提示token数 + 补全token数 × 补全倍率)/ 500000 (单位:美元)')}
  544. </span>
  545. </div>
  546. </div>
  547. </div>
  548. <div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-yellow-400 via-orange-400 to-red-400" style={{ opacity: 0.6 }}></div>
  549. </div>
  550. </Card>
  551. {/* 模型分类 Tabs */}
  552. <div className="mb-6">
  553. {renderTabs()}
  554. {/* 搜索和表格区域 */}
  555. {SearchAndActions}
  556. {ModelTable}
  557. </div>
  558. {/* 倍率说明图预览 */}
  559. <ImagePreview
  560. src={modalImageUrl}
  561. visible={isModalOpenurl}
  562. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  563. />
  564. </Card>
  565. </div>
  566. </div>
  567. </Layout.Content>
  568. </Layout>
  569. </div>
  570. );
  571. };
  572. export default ModelPricing;