Skip to content

Commit 45e6f64

Browse files
committed
Separate prompt and completion tokens
1 parent 011f122 commit 45e6f64

File tree

4 files changed

+34
-4
lines changed

4 files changed

+34
-4
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/*
2+
Warnings:
3+
4+
- Added the required column `completionTokens` to the `token_stats` table without a default value. This is not possible if the table is not empty.
5+
- Added the required column `promptTokens` to the `token_stats` table without a default value. This is not possible if the table is not empty.
6+
7+
*/
8+
-- AlterTable
9+
ALTER TABLE "token_stats" ADD COLUMN "completionTokens" INTEGER NOT NULL,
10+
ADD COLUMN "promptTokens" INTEGER NOT NULL;

prisma/schema.prisma

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ model TokenStat {
6767
id String @id @default(cuid())
6868
userId String
6969
messageIds String[]
70+
promptTokens Int
71+
completionTokens Int
7072
totalTokens Int
7173
createdAt DateTime @default(now())
7274
updatedAt DateTime @updatedAt

src/app/api/chat/route.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -165,13 +165,25 @@ export async function POST(req: Request) {
165165
});
166166

167167
// Save the token stats
168-
if (messages && newUserMessage && !isNaN(usage.totalTokens)) {
168+
if (
169+
messages &&
170+
newUserMessage &&
171+
!isNaN(usage.promptTokens) &&
172+
!isNaN(usage.completionTokens) &&
173+
!isNaN(usage.totalTokens)
174+
) {
169175
const messageIds = newUserMessage
170176
.concat(messages)
171177
.map((message) => message.id);
172-
const totalTokens = usage.totalTokens;
173-
174-
await dbCreateTokenStat({ userId, messageIds, totalTokens });
178+
const { promptTokens, completionTokens, totalTokens } = usage;
179+
180+
await dbCreateTokenStat({
181+
userId,
182+
messageIds,
183+
promptTokens,
184+
completionTokens,
185+
totalTokens,
186+
});
175187
}
176188

177189
revalidatePath('/api/conversations');

src/server/db/queries.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,17 +167,23 @@ export async function dbCreateTokenStat({
167167
userId,
168168
messageIds,
169169
totalTokens,
170+
promptTokens,
171+
completionTokens,
170172
}: {
171173
userId: string;
172174
messageIds: string[];
173175
totalTokens: number;
176+
promptTokens: number;
177+
completionTokens: number;
174178
}) {
175179
try {
176180
return await prisma.tokenStat.create({
177181
data: {
178182
userId,
179183
messageIds,
180184
totalTokens,
185+
promptTokens,
186+
completionTokens,
181187
},
182188
});
183189
} catch (error) {

0 commit comments

Comments
 (0)