ModelPricing.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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) => a.available - b.available,
  105. },
  106. {
  107. title: t('模型名称'),
  108. dataIndex: 'model_name',
  109. render: (text, record, index) => {
  110. return (
  111. <>
  112. <Tag
  113. color='green'
  114. size='large'
  115. onClick={() => {
  116. copyText(text);
  117. }}
  118. >
  119. {text}
  120. </Tag>
  121. </>
  122. );
  123. },
  124. onFilter: (value, record) =>
  125. record.model_name.toLowerCase().includes(value.toLowerCase()),
  126. filteredValue,
  127. },
  128. {
  129. title: t('计费类型'),
  130. dataIndex: 'quota_type',
  131. render: (text, record, index) => {
  132. return renderQuotaType(parseInt(text));
  133. },
  134. sorter: (a, b) => a.quota_type - b.quota_type,
  135. },
  136. {
  137. title: t('可用分组'),
  138. dataIndex: 'enable_groups',
  139. render: (text, record, index) => {
  140. // enable_groups is a string array
  141. return (
  142. <Space>
  143. {text.map((group) => {
  144. if (usableGroup[group]) {
  145. if (group === selectedGroup) {
  146. return (
  147. <Tag
  148. color='blue'
  149. size='large'
  150. prefixIcon={<IconVerify />}
  151. >
  152. {group}
  153. </Tag>
  154. );
  155. } else {
  156. return (
  157. <Tag
  158. color='blue'
  159. size='large'
  160. onClick={() => {
  161. setSelectedGroup(group);
  162. showInfo(t('当前查看的分组为:{{group}},倍率为:{{ratio}}', {
  163. group: group,
  164. ratio: groupRatio[group]
  165. }));
  166. }}
  167. >
  168. {group}
  169. </Tag>
  170. );
  171. }
  172. }
  173. })}
  174. </Space>
  175. );
  176. },
  177. },
  178. {
  179. title: () => (
  180. <span style={{'display':'flex','alignItems':'center'}}>
  181. {t('倍率')}
  182. <Popover
  183. content={
  184. <div style={{ padding: 8 }}>
  185. {t('倍率是为了方便换算不同价格的模型')}<br/>
  186. {t('点击查看倍率说明')}
  187. </div>
  188. }
  189. position='top'
  190. style={{
  191. backgroundColor: 'rgba(var(--semi-blue-4),1)',
  192. borderColor: 'rgba(var(--semi-blue-4),1)',
  193. color: 'var(--semi-color-white)',
  194. borderWidth: 1,
  195. borderStyle: 'solid',
  196. }}
  197. >
  198. <IconHelpCircle
  199. onClick={() => {
  200. setModalImageUrl('/ratio.png');
  201. setIsModalOpenurl(true);
  202. }}
  203. />
  204. </Popover>
  205. </span>
  206. ),
  207. dataIndex: 'model_ratio',
  208. render: (text, record, index) => {
  209. let content = text;
  210. let completionRatio = parseFloat(record.completion_ratio.toFixed(3));
  211. content = (
  212. <>
  213. <Text>{t('模型倍率')}:{record.quota_type === 0 ? text : t('无')}</Text>
  214. <br />
  215. <Text>{t('补全倍率')}:{record.quota_type === 0 ? completionRatio : t('无')}</Text>
  216. <br />
  217. <Text>{t('分组倍率')}:{groupRatio[selectedGroup]}</Text>
  218. </>
  219. );
  220. return <div>{content}</div>;
  221. },
  222. },
  223. {
  224. title: t('模型价格'),
  225. dataIndex: 'model_price',
  226. render: (text, record, index) => {
  227. let content = text;
  228. if (record.quota_type === 0) {
  229. // 这里的 *2 是因为 1倍率=0.002刀,请勿删除
  230. let inputRatioPrice = record.model_ratio * 2 * groupRatio[selectedGroup];
  231. let completionRatioPrice =
  232. record.model_ratio *
  233. record.completion_ratio * 2 *
  234. groupRatio[selectedGroup];
  235. content = (
  236. <>
  237. <Text>{t('提示')} ${inputRatioPrice} / 1M tokens</Text>
  238. <br />
  239. <Text>{t('补全')} ${completionRatioPrice} / 1M tokens</Text>
  240. </>
  241. );
  242. } else {
  243. let price = parseFloat(text) * groupRatio[selectedGroup];
  244. content = <>${t('模型价格')}:${price}</>;
  245. }
  246. return <div>{content}</div>;
  247. },
  248. },
  249. ];
  250. const [models, setModels] = useState([]);
  251. const [loading, setLoading] = useState(true);
  252. const [userState, userDispatch] = useContext(UserContext);
  253. const [groupRatio, setGroupRatio] = useState({});
  254. const [usableGroup, setUsableGroup] = useState({});
  255. const setModelsFormat = (models, groupRatio) => {
  256. for (let i = 0; i < models.length; i++) {
  257. models[i].key = models[i].model_name;
  258. models[i].group_ratio = groupRatio[models[i].model_name];
  259. }
  260. // sort by quota_type
  261. models.sort((a, b) => {
  262. return a.quota_type - b.quota_type;
  263. });
  264. // sort by model_name, start with gpt is max, other use localeCompare
  265. models.sort((a, b) => {
  266. if (a.model_name.startsWith('gpt') && !b.model_name.startsWith('gpt')) {
  267. return -1;
  268. } else if (
  269. !a.model_name.startsWith('gpt') &&
  270. b.model_name.startsWith('gpt')
  271. ) {
  272. return 1;
  273. } else {
  274. return a.model_name.localeCompare(b.model_name);
  275. }
  276. });
  277. setModels(models);
  278. };
  279. const loadPricing = async () => {
  280. setLoading(true);
  281. let url = '';
  282. url = `/api/pricing`;
  283. const res = await API.get(url);
  284. const { success, message, data, group_ratio, usable_group } = res.data;
  285. if (success) {
  286. setGroupRatio(group_ratio);
  287. setUsableGroup(usable_group);
  288. setSelectedGroup(userState.user ? userState.user.group : 'default')
  289. setModelsFormat(data, group_ratio);
  290. } else {
  291. showError(message);
  292. }
  293. setLoading(false);
  294. };
  295. const refresh = async () => {
  296. await loadPricing();
  297. };
  298. const copyText = async (text) => {
  299. if (await copy(text)) {
  300. showSuccess('已复制:' + text);
  301. } else {
  302. // setSearchKeyword(text);
  303. Modal.error({ title: '无法复制到剪贴板,请手动复制', content: text });
  304. }
  305. };
  306. useEffect(() => {
  307. refresh().then();
  308. }, []);
  309. return (
  310. <>
  311. <Layout>
  312. {userState.user ? (
  313. <Banner
  314. type="success"
  315. fullMode={false}
  316. closeIcon="null"
  317. description={t('您的默认分组为:{{group}},分组倍率为:{{ratio}}', {
  318. group: userState.user.group,
  319. ratio: groupRatio[userState.user.group]
  320. })}
  321. />
  322. ) : (
  323. <Banner
  324. type='warning'
  325. fullMode={false}
  326. closeIcon="null"
  327. description={t('您还未登陆,显示的价格为默认分组倍率: {{ratio}}', {
  328. ratio: groupRatio['default']
  329. })}
  330. />
  331. )}
  332. <br/>
  333. <Banner
  334. type="info"
  335. fullMode={false}
  336. description={<div>{t('按量计费费用 = 分组倍率 × 模型倍率 × (提示token数 + 补全token数 × 补全倍率)/ 500000 (单位:美元)')}</div>}
  337. closeIcon="null"
  338. />
  339. <br/>
  340. <Space style={{ marginBottom: 16 }}>
  341. <Input
  342. placeholder={t('模糊搜索模型名称')}
  343. style={{ width: 200 }}
  344. onCompositionStart={handleCompositionStart}
  345. onCompositionEnd={handleCompositionEnd}
  346. onChange={handleChange}
  347. showClear
  348. />
  349. <Button
  350. theme='light'
  351. type='tertiary'
  352. style={{width: 150}}
  353. onClick={() => {
  354. copyText(selectedRowKeys);
  355. }}
  356. disabled={selectedRowKeys == ""}
  357. >
  358. {t('复制选中模型')}
  359. </Button>
  360. </Space>
  361. <Table
  362. style={{ marginTop: 5 }}
  363. columns={columns}
  364. dataSource={models}
  365. loading={loading}
  366. pagination={{
  367. formatPageText: (page) =>
  368. t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
  369. start: page.currentStart,
  370. end: page.currentEnd,
  371. total: models.length
  372. }),
  373. pageSize: models.length,
  374. showSizeChanger: false,
  375. }}
  376. rowSelection={rowSelection}
  377. />
  378. <ImagePreview
  379. src={modalImageUrl}
  380. visible={isModalOpenurl}
  381. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  382. />
  383. </Layout>
  384. </>
  385. );
  386. };
  387. export default ModelPricing;