更新token的计算方式

This commit is contained in:
sijinhui 2024-05-08 22:28:55 +08:00
parent 69e34644d6
commit e214302817
3 changed files with 97 additions and 38 deletions

View File

@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { addHours, subMinutes } from "date-fns";
// import { addHours, subMinutes } from "date-fns";
import { EChartsOption } from "echarts";
import { getCurStartEnd } from "@/app/utils/custom";

View File

@ -1,11 +1,49 @@
import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getTokenLength } from "@/lib/utils";
import { getSession } from "@/lib/auth";
import { getCurStartEnd } from "@/app/utils/custom";
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
// 判断网址和请求方法
const method = req.method;
// const url = req.url;
const { pathname, searchParams } = new URL(req.url);
const searchText = searchParams.get("search");
if (method === "GET") {
try {
const session = await getSession();
const user_id = session?.user.id;
const { startOfTheDayInTimeZone, endOfTheDayInTimeZone } =
getCurStartEnd();
const current_token = await prisma.logEntry
.findMany({
where: {
userID: user_id,
createdAt: {
gte: startOfTheDayInTimeZone.toISOString(), // gte 表示 '大于等于'
lte: endOfTheDayInTimeZone.toISOString(), // lte 表示 '小于等于'
},
},
select: {
logToken: true,
},
})
.then((result) => {
return result.reduce(
(acc, cur) => (cur.logToken ? acc + cur.logToken : acc),
0,
);
});
// console.log('-----------', user_id, current_token)
return NextResponse.json({ result: { current_token: current_token } });
} catch {}
return NextResponse.json({ error: "未知错误" }, { status: 500 });
}
try {
const request_data = await req.json();
try {
@ -43,7 +81,7 @@ async function handle(
return NextResponse.json({ status: 1 });
}
// export const GET = handle;
export const GET = handle;
export const POST = handle;
// export const runtime = "edge";

View File

@ -101,7 +101,7 @@ import { getClientConfig } from "../config/client";
import Image from "next/image";
import { useAllModels } from "../utils/hooks";
import { MultimodalContent } from "../client/api";
import { getTokenLength } from "@/lib/utils";
// import { getTokenLength } from "@/lib/utils";
import VoiceInput from "./voice-input";
// import GptPrompts from "./gpt-prompts";
// const VoiceInput = dynamic(
@ -1268,6 +1268,27 @@ function _Chat() {
setAttachImages(images);
}
useEffect(() => {
if (!isLoading) {
try {
fetch("/api/logs/get_current_token", {
method: "GET",
credentials: "include",
})
.then((response) => response.json())
.then((result) => {
console.log("请求成功,", result);
localStorage.setItem(
"current_day_token",
result["result"]["current_token"],
);
});
} catch {}
console.log("加载消息完成。获取token");
}
}, [isLoading]);
// const [ voiceInputText, setVoiceInputText ] = useState("");
// const [ voiceInputLoading, setVoiceInputLoading ] = useState(false);
@ -1756,45 +1777,45 @@ function _Chat() {
);
}
function getCurrentDayToken(sessions: ChatSession[]): number {
try {
const currentTime = new Date();
const startOfTheDayInTimeZone = new Date(
currentTime.getFullYear(),
currentTime.getMonth(),
currentTime.getDate(),
0,
0,
0,
);
const current_day_message = sessions
.reduce((acc, item) => {
// @ts-ignore
return acc.concat(item.messages);
}, [])
.filter((item1) => {
// @ts-ignore
const dateToCheck = new Date(item1.date);
return startOfTheDayInTimeZone < dateToCheck;
});
const all_current_day_content = current_day_message
// @ts-ignore
.map((item) => item.content)
.join(" ");
// 获取会话之后再整合content
return getTokenLength(all_current_day_content);
} catch (e) {
return 0;
}
}
// function getCurrentDayToken(sessions: ChatSession[]): number {
// try {
// const currentTime = new Date();
// const startOfTheDayInTimeZone = new Date(
// currentTime.getFullYear(),
// currentTime.getMonth(),
// currentTime.getDate(),
// 0,
// 0,
// 0,
// );
// const current_day_message = sessions
// .reduce((acc, item) => {
// // @ts-ignore
// return acc.concat(item.messages);
// }, [])
// .filter((item1) => {
// // @ts-ignore
// const dateToCheck = new Date(item1.date);
// return startOfTheDayInTimeZone < dateToCheck;
// });
// const all_current_day_content = current_day_message
// // @ts-ignore
// .map((item) => item.content)
// .join(" ");
// // 获取会话之后再整合content
// return getTokenLength(all_current_day_content);
// } catch (e) {
// return 0;
// }
// }
export function Chat() {
const chatStore = useChatStore();
const sessionIndex = chatStore.currentSessionIndex;
// 这里计先计算一下当天总token数。
localStorage.setItem(
"current_day_token",
String(getCurrentDayToken(chatStore.sessions)),
);
// localStorage.setItem(
// "current_day_token",
// String(getCurrentDayToken(chatStore.sessions)),
// );
return <_Chat key={sessionIndex}></_Chat>;
}