feat: 修改计费模式为tokens

This commit is contained in:
archer
2023-03-25 14:43:32 +08:00
parent 4eaf3a1be0
commit 6bba859060
18 changed files with 97 additions and 38 deletions

View File

@@ -1,41 +1,49 @@
import { connectToDatabase, Bill, User } from '../mongo';
import { modelList } from '@/constants/model';
import { encode } from 'gpt-token-utils';
import { formatPrice } from '@/utils/user';
export const pushBill = async ({
modelName,
userId,
chatId,
textLen
text
}: {
modelName: string;
userId: string;
chatId: string;
textLen: number;
text: string;
}) => {
await connectToDatabase();
let billId;
try {
// 获取模型单价格
const modelItem = modelList.find((item) => item.model === modelName);
const unitPrice = modelItem?.price || 5;
if (!modelItem) return;
// 计算 token 数量
const tokens = encode(text);
const price = modelItem.price * textLen;
// 计算价格
const price = unitPrice * tokens.length;
console.log('token len:', tokens.length, 'price: ', `${formatPrice(price)}`);
try {
// 插入 Bill 记录
const res = await Bill.create({
userId,
type: 'chat',
modelName: modelItem.model,
modelName,
chatId,
textLen,
textLen: text.length,
tokenLen: tokens.length,
price
});
billId = res._id;
// 扣费
// 账号扣费
await User.findByIdAndUpdate(userId, {
$inc: { balance: -price }
});

View File

@@ -31,6 +31,11 @@ const BillSchema = new Schema({
type: Number,
required: true
},
tokenLen: {
// 折算成 token 的数量
type: Number,
required: true
},
price: {
type: Number,
required: true

View File

@@ -1,5 +1,6 @@
import { Schema, model, models } from 'mongoose';
import { hashPassword } from '@/service/utils/tools';
import { PRICE_SCALE } from '@/utils/user';
const UserSchema = new Schema({
email: {
@@ -16,7 +17,7 @@ const UserSchema = new Schema({
},
balance: {
type: Number,
default: 0.5 * 100000
default: 0.5 * PRICE_SCALE
},
accounts: [
{