ModelPricing.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. Banner,
  6. Input,
  7. Layout,
  8. Modal,
  9. Space,
  10. Table,
  11. Tag,
  12. Tooltip,
  13. Popover,
  14. ImagePreview,
  15. Button,
  16. } from '@douyinfe/semi-ui';
  17. import {
  18. IconMore,
  19. IconVerify,
  20. IconUploadError,
  21. IconHelpCircle,
  22. } from '@douyinfe/semi-icons';
  23. import { UserContext } from '../context/User/index.js';
  24. import Text from '@douyinfe/semi-ui/lib/es/typography/text';
  25. const ModelPricing = () => {
  26. const { t } = useTranslation();
  27. const [filteredValue, setFilteredValue] = useState([]);
  28. const compositionRef = useRef({ isComposition: false });
  29. const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  30. const [modalImageUrl, setModalImageUrl] = useState('');
  31. const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  32. const [selectedGroup, setSelectedGroup] = useState('default');
  33. const rowSelection = useMemo(
  34. () => ({
  35. onChange: (selectedRowKeys, selectedRows) => {
  36. setSelectedRowKeys(selectedRowKeys);
  37. },
  38. }),
  39. [],
  40. );
  41. const handleChange = (value) => {
  42. if (compositionRef.current.isComposition) {
  43. return;
  44. }
  45. const newFilteredValue = value ? [value] : [];
  46. setFilteredValue(newFilteredValue);
  47. };
  48. const handleCompositionStart = () => {
  49. compositionRef.current.isComposition = true;
  50. };
  51. const handleCompositionEnd = (event) => {
  52. compositionRef.current.isComposition = false;
  53. const value = event.target.value;
  54. const newFilteredValue = value ? [value] : [];
  55. setFilteredValue(newFilteredValue);
  56. };
  57. function renderQuotaType(type) {
  58. // Ensure all cases are string literals by adding quotes.
  59. switch (type) {
  60. case 1:
  61. return (
  62. <Tag color='teal' size='large'>
  63. {t('按次计费')}
  64. </Tag>
  65. );
  66. case 0:
  67. return (
  68. <Tag color='violet' size='large'>
  69. {t('按量计费')}
  70. </Tag>
  71. );
  72. default:
  73. return t('未知');
  74. }
  75. }
  76. function renderAvailable(available) {
  77. return available ? (
  78. <Popover
  79. content={
  80. <div style={{ padding: 8 }}>{t('您的分组可以使用该模型')}</div>
  81. }
  82. position='top'
  83. key={available}
  84. style={{
  85. backgroundColor: 'rgba(var(--semi-blue-4),1)',
  86. borderColor: 'rgba(var(--semi-blue-4),1)',
  87. color: 'var(--semi-color-white)',
  88. borderWidth: 1,
  89. borderStyle: 'solid',
  90. }}
  91. >
  92. <IconVerify style={{ color: 'green' }} size='large' />
  93. </Popover>
  94. ) : null;
  95. }
  96. const columns = [
  97. {
  98. title: t('可用性'),
  99. dataIndex: 'available',
  100. render: (text, record, index) => {
  101. // if record.enable_groups contains selectedGroup, then available is true
  102. return renderAvailable(record.enable_groups.includes(selectedGroup));
  103. },
  104. sorter: (a, b) => {
  105. const aAvailable = a.enable_groups.includes(selectedGroup);
  106. const bAvailable = b.enable_groups.includes(selectedGroup);
  107. return Number(aAvailable) - Number(bAvailable);
  108. },
  109. defaultSortOrder: 'descend',
  110. },
  111. {
  112. title: t('模型名称'),
  113. dataIndex: 'model_name',
  114. render: (text, record, index) => {
  115. return (
  116. <>
  117. <Tag
  118. color='green'
  119. size='large'
  120. onClick={() => {
  121. copyText(text);
  122. }}
  123. >
  124. {text}
  125. </Tag>
  126. </>
  127. );
  128. },
  129. onFilter: (value, record) =>
  130. record.model_name.toLowerCase().includes(value.toLowerCase()),
  131. filteredValue,
  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. },
  141. {
  142. title: t('可用分组'),
  143. dataIndex: 'enable_groups',
  144. render: (text, record, index) => {
  145. // enable_groups is a string array
  146. return (
  147. <Space>
  148. {text.map((group) => {
  149. if (usableGroup[group]) {
  150. if (group === selectedGroup) {
  151. return (
  152. <Tag color='blue' size='large' 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. >
  171. {group}
  172. </Tag>
  173. );
  174. }
  175. }
  176. })}
  177. </Space>
  178. );
  179. },
  180. },
  181. {
  182. title: () => (
  183. <span style={{ display: 'flex', alignItems: 'center' }}>
  184. {t('倍率')}
  185. <Popover
  186. content={
  187. <div style={{ padding: 8 }}>
  188. {t('倍率是为了方便换算不同价格的模型')}
  189. <br />
  190. {t('点击查看倍率说明')}
  191. </div>
  192. }
  193. position='top'
  194. style={{
  195. backgroundColor: 'rgba(var(--semi-blue-4),1)',
  196. borderColor: 'rgba(var(--semi-blue-4),1)',
  197. color: 'var(--semi-color-white)',
  198. borderWidth: 1,
  199. borderStyle: 'solid',
  200. }}
  201. >
  202. <IconHelpCircle
  203. onClick={() => {
  204. setModalImageUrl('/ratio.png');
  205. setIsModalOpenurl(true);
  206. }}
  207. />
  208. </Popover>
  209. </span>
  210. ),
  211. dataIndex: 'model_ratio',
  212. render: (text, record, index) => {
  213. let content = text;
  214. let completionRatio = parseFloat(record.completion_ratio.toFixed(3));
  215. content = (
  216. <>
  217. <Text>
  218. {t('模型倍率')}:{record.quota_type === 0 ? text : t('无')}
  219. </Text>
  220. <br />
  221. <Text>
  222. {t('补全倍率')}:
  223. {record.quota_type === 0 ? completionRatio : t('无')}
  224. </Text>
  225. <br />
  226. <Text>
  227. {t('分组倍率')}:{groupRatio[selectedGroup]}
  228. </Text>
  229. </>
  230. );
  231. return <div>{content}</div>;
  232. },
  233. },
  234. {
  235. title: t('模型价格'),
  236. dataIndex: 'model_price',
  237. render: (text, record, index) => {
  238. let content = text;
  239. if (record.quota_type === 0) {
  240. // 这里的 *2 是因为 1倍率=0.002刀,请勿删除
  241. let inputRatioPrice =
  242. record.model_ratio * 2 * groupRatio[selectedGroup];
  243. let completionRatioPrice =
  244. record.model_ratio *
  245. record.completion_ratio *
  246. 2 *
  247. groupRatio[selectedGroup];
  248. content = (
  249. <>
  250. <Text>
  251. {t('提示')} ${inputRatioPrice} / 1M tokens
  252. </Text>
  253. <br />
  254. <Text>
  255. {t('补全')} ${completionRatioPrice} / 1M tokens
  256. </Text>
  257. </>
  258. );
  259. } else {
  260. let price = parseFloat(text) * groupRatio[selectedGroup];
  261. content = (
  262. <>
  263. ${t('模型价格')}:${price}
  264. </>
  265. );
  266. }
  267. return <div>{content}</div>;
  268. },
  269. },
  270. ];
  271. const [models, setModels] = useState([]);
  272. const [loading, setLoading] = useState(true);
  273. const [userState, userDispatch] = useContext(UserContext);
  274. const [groupRatio, setGroupRatio] = useState({});
  275. const [usableGroup, setUsableGroup] = useState({});
  276. const setModelsFormat = (models, groupRatio) => {
  277. for (let i = 0; i < models.length; i++) {
  278. models[i].key = models[i].model_name;
  279. models[i].group_ratio = groupRatio[models[i].model_name];
  280. }
  281. // sort by quota_type
  282. models.sort((a, b) => {
  283. return a.quota_type - b.quota_type;
  284. });
  285. // sort by model_name, start with gpt is max, other use localeCompare
  286. models.sort((a, b) => {
  287. if (a.model_name.startsWith('gpt') && !b.model_name.startsWith('gpt')) {
  288. return -1;
  289. } else if (
  290. !a.model_name.startsWith('gpt') &&
  291. b.model_name.startsWith('gpt')
  292. ) {
  293. return 1;
  294. } else {
  295. return a.model_name.localeCompare(b.model_name);
  296. }
  297. });
  298. setModels(models);
  299. };
  300. const loadPricing = async () => {
  301. setLoading(true);
  302. let url = '';
  303. url = `/api/pricing`;
  304. const res = await API.get(url);
  305. const { success, message, data, group_ratio, usable_group } = res.data;
  306. if (success) {
  307. setGroupRatio(group_ratio);
  308. setUsableGroup(usable_group);
  309. setSelectedGroup(userState.user ? userState.user.group : 'default');
  310. setModelsFormat(data, group_ratio);
  311. } else {
  312. showError(message);
  313. }
  314. setLoading(false);
  315. };
  316. const refresh = async () => {
  317. await loadPricing();
  318. };
  319. const copyText = async (text) => {
  320. if (await copy(text)) {
  321. showSuccess('已复制:' + text);
  322. } else {
  323. // setSearchKeyword(text);
  324. Modal.error({ title: '无法复制到剪贴板,请手动复制', content: text });
  325. }
  326. };
  327. useEffect(() => {
  328. refresh().then();
  329. }, []);
  330. return (
  331. <>
  332. <Layout>
  333. {userState.user ? (
  334. <Banner
  335. type='success'
  336. fullMode={false}
  337. closeIcon='null'
  338. description={t('您的默认分组为:{{group}},分组倍率为:{{ratio}}', {
  339. group: userState.user.group,
  340. ratio: groupRatio[userState.user.group],
  341. })}
  342. />
  343. ) : (
  344. <Banner
  345. type='warning'
  346. fullMode={false}
  347. closeIcon='null'
  348. description={t('您还未登陆,显示的价格为默认分组倍率: {{ratio}}', {
  349. ratio: groupRatio['default'],
  350. })}
  351. />
  352. )}
  353. <br />
  354. <Banner
  355. type='info'
  356. fullMode={false}
  357. description={
  358. <div>
  359. {t(
  360. '按量计费费用 = 分组倍率 × 模型倍率 × (提示token数 + 补全token数 × 补全倍率)/ 500000 (单位:美元)',
  361. )}
  362. </div>
  363. }
  364. closeIcon='null'
  365. />
  366. <br />
  367. <Space style={{ marginBottom: 16 }}>
  368. <Input
  369. placeholder={t('模糊搜索模型名称')}
  370. style={{ width: 200 }}
  371. onCompositionStart={handleCompositionStart}
  372. onCompositionEnd={handleCompositionEnd}
  373. onChange={handleChange}
  374. showClear
  375. />
  376. <Button
  377. theme='light'
  378. type='tertiary'
  379. style={{ width: 150 }}
  380. onClick={() => {
  381. copyText(selectedRowKeys);
  382. }}
  383. disabled={selectedRowKeys == ''}
  384. >
  385. {t('复制选中模型')}
  386. </Button>
  387. </Space>
  388. <Table
  389. style={{ marginTop: 5 }}
  390. columns={columns}
  391. dataSource={models}
  392. loading={loading}
  393. pagination={{
  394. formatPageText: (page) =>
  395. t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
  396. start: page.currentStart,
  397. end: page.currentEnd,
  398. total: models.length,
  399. }),
  400. pageSize: models.length,
  401. showSizeChanger: false,
  402. }}
  403. rowSelection={rowSelection}
  404. />
  405. <ImagePreview
  406. src={modalImageUrl}
  407. visible={isModalOpenurl}
  408. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  409. />
  410. </Layout>
  411. </>
  412. );
  413. };
  414. export default ModelPricing;