Skip to content

Commit 681a87f

Browse files
committed
fix: Modify backend token calculation to be asynchronous
1 parent dcb2555 commit 681a87f

File tree

4 files changed

+20
-39
lines changed

4 files changed

+20
-39
lines changed

CHANGE_LOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
> 2023-06-11
66
7+
### Fixed
8+
9+
- Change the backend token calculation to asynchronous, otherwise it will cause inaccurate calculations.
10+
711
### Add
812

913
- Added backend capability to calculate token consumption

CHANGE_LOG.zh_CN.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
> 2023-06-11
66
7+
### Fixed
8+
9+
- 后端计算 token 修改为异步,不然会导致计算不准确
10+
711
### Add
812

913
- 新增后端计算 token 消耗的能力

src/app/api/azure/route.ts

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -73,26 +73,20 @@ const stream = async (
7373
const tokenInfo = new GPTTokens({ model, messages: final });
7474
const { usedTokens, usedUSD } = tokenInfo;
7575

76-
prisma.user
77-
.findUnique({
76+
const findUser = await prisma.user.findUnique({
77+
where: { id: userId },
78+
});
79+
if (findUser) {
80+
const costTokens = findUser.costTokens + usedTokens;
81+
const costUSD = Number((findUser.costUSD + usedUSD).toFixed(5));
82+
await prisma.user.update({
7883
where: { id: userId },
79-
})
80-
.then((findUser) => {
81-
if (!findUser) return;
82-
83-
const costTokens = findUser.costTokens + usedTokens;
84-
const costUSD = Number((findUser.costUSD + usedUSD).toFixed(5));
85-
86-
prisma.user
87-
.update({
88-
where: { id: userId },
89-
data: {
90-
costTokens,
91-
costUSD,
92-
},
93-
})
94-
.then();
84+
data: {
85+
costTokens,
86+
costUSD,
87+
},
9588
});
89+
}
9690
}
9791

9892
if (buffer) {

src/app/api/openai/route.ts

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -95,27 +95,6 @@ const stream = async (
9595
},
9696
});
9797
}
98-
99-
// prisma.user
100-
// .findUnique({
101-
// where: { id: userId },
102-
// })
103-
// .then((findUser) => {
104-
// if (!findUser) return;
105-
106-
// const costTokens = findUser.costTokens + usedTokens;
107-
// const costUSD = Number((findUser.costUSD + usedUSD).toFixed(5));
108-
109-
// prisma.user
110-
// .update({
111-
// where: { id: userId },
112-
// data: {
113-
// costTokens,
114-
// costUSD,
115-
// },
116-
// })
117-
// .then();
118-
// });
11998
}
12099

121100
if (buffer) {

0 commit comments

Comments
 (0)