feat: 拆分文本账单结算

This commit is contained in:
archer
2023-03-25 23:02:55 +08:00
parent 02cee35a45
commit 75cf3d1e9f
17 changed files with 191 additions and 89 deletions

View File

@@ -4,6 +4,7 @@ import { httpsAgent, getOpenApiKey } from '@/service/utils/tools';
import type { ChatCompletionRequestMessage } from 'openai';
import { DataItemSchema } from '@/types/mongoSchema';
import { ChatModelNameEnum } from '@/constants/model';
import { pushSplitDataBill } from '@/service/events/pushBill';
export async function generateQA(next = false): Promise<any> {
if (global.generatingQA && !next) return;
@@ -83,20 +84,21 @@ export async function generateQA(next = false): Promise<any> {
const splitResponse = splitText(content || '');
// 插入数据库,并修改状态
await DataItem.findByIdAndUpdate(dataItem._id, {
status: dataItem.temperature >= 80 ? 0 : 1, // 需要生成 5 组内容。0,0.2,0.4,0.6,0.8
temperature: dataItem.temperature >= 80 ? dataItem.temperature : dataItem.temperature + 20,
status: dataItem.temperature >= 90 ? 0 : 1, // 需要生成 4 组内容。0,0.3,0.6,0.9
temperature: dataItem.temperature >= 90 ? dataItem.temperature : dataItem.temperature + 30,
$push: {
result: {
$each: splitResponse
}
}
});
console.log(
'生成成功time:',
`${(Date.now() - startTime) / 1000}s`,
'result length: ',
splitResponse.length
);
// 计费
!userApiKey &&
pushSplitDataBill({
userId: dataItem.userId,
text: systemPrompt.content + dataItem.text + content
});
console.log('生成QA成功time:', `${(Date.now() - startTime) / 1000}s`);
} catch (error: any) {
console.log('error: 生成QA错误', dataItem?._id);
console.log('response:', error?.response);

View File

@@ -0,0 +1,105 @@
import { connectToDatabase, Bill, User } from '../mongo';
import { modelList, ChatModelNameEnum } from '@/constants/model';
import { encode } from 'gpt-token-utils';
import { formatPrice } from '@/utils/user';
export const pushChatBill = async ({
modelName,
userId,
chatId,
text
}: {
modelName: string;
userId: string;
chatId: string;
text: string;
}) => {
await connectToDatabase();
let billId;
try {
// 获取模型单价格
const modelItem = modelList.find((item) => item.model === modelName);
const unitPrice = modelItem?.price || 5;
// 计算 token 数量
const tokens = encode(text);
// 计算价格
const price = unitPrice * tokens.length;
console.log('chat bill');
console.log('token len:', tokens.length);
console.log('text len: ', text.length);
console.log('price: ', `${formatPrice(price)}`);
try {
// 插入 Bill 记录
const res = await Bill.create({
userId,
type: 'chat',
modelName,
chatId,
textLen: text.length,
tokenLen: tokens.length,
price
});
billId = res._id;
// 账号扣费
await User.findByIdAndUpdate(userId, {
$inc: { balance: -price }
});
} catch (error) {
console.log('创建账单失败:', error);
billId && Bill.findByIdAndDelete(billId);
}
} catch (error) {
console.log(error);
}
};
export const pushSplitDataBill = async ({ userId, text }: { userId: string; text: string }) => {
await connectToDatabase();
let billId;
try {
// 获取模型单价格, 都是用 gpt35 拆分
const modelItem = modelList.find((item) => item.model === ChatModelNameEnum.GPT35);
const unitPrice = modelItem?.price || 5;
// 计算 token 数量
const tokens = encode(text);
// 计算价格
const price = unitPrice * tokens.length;
console.log('splitData bill');
console.log('token len:', tokens.length);
console.log('text len: ', text.length);
console.log('price: ', `${formatPrice(price)}`);
try {
// 插入 Bill 记录
const res = await Bill.create({
userId,
type: 'splitData',
modelName: ChatModelNameEnum.GPT35,
textLen: text.length,
tokenLen: tokens.length,
price
});
billId = res._id;
// 账号扣费
await User.findByIdAndUpdate(userId, {
$inc: { balance: -price }
});
} catch (error) {
console.log('创建账单失败:', error);
billId && Bill.findByIdAndDelete(billId);
}
} catch (error) {
console.log(error);
}
};

View File

@@ -1,58 +0,0 @@
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,
text
}: {
modelName: string;
userId: string;
chatId: string;
text: string;
}) => {
await connectToDatabase();
let billId;
try {
// 获取模型单价格
const modelItem = modelList.find((item) => item.model === modelName);
const unitPrice = modelItem?.price || 5;
// 计算 token 数量
const tokens = encode(text);
// 计算价格
const price = unitPrice * tokens.length;
console.log('token len:', tokens.length);
console.log('text len: ', text.length);
console.log('price: ', `${formatPrice(price)}`);
try {
// 插入 Bill 记录
const res = await Bill.create({
userId,
type: 'chat',
modelName,
chatId,
textLen: text.length,
tokenLen: tokens.length,
price
});
billId = res._id;
// 账号扣费
await User.findByIdAndUpdate(userId, {
$inc: { balance: -price }
});
} catch (error) {
billId && Bill.findByIdAndDelete(billId);
}
} catch (error) {
console.log(error);
}
};

View File

@@ -10,7 +10,7 @@ const BillSchema = new Schema({
},
type: {
type: String,
enum: ['chat', 'generateData', 'return'],
enum: ['chat', 'splitData', 'return'],
required: true
},
modelName: {
@@ -20,8 +20,7 @@ const BillSchema = new Schema({
},
chatId: {
type: Schema.Types.ObjectId,
ref: 'chat',
required: true
ref: 'chat'
},
time: {
type: Date,