Merge pull request #87 from sijinhui/dev

更新token的计算方式
This commit is contained in:
sijinhui 2024-05-08 22:53:52 +08:00 committed by GitHub
commit 43b28ac645
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 100 additions and 38 deletions

View File

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

View File

@ -1,11 +1,49 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma"; import prisma from "@/lib/prisma";
import { getTokenLength } from "@/lib/utils"; import { getTokenLength } from "@/lib/utils";
import { getSession } from "@/lib/auth";
import { getCurStartEnd } from "@/app/utils/custom";
async function handle( async function handle(
req: NextRequest, req: NextRequest,
{ params }: { params: { path: string[] } }, { 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 { try {
const request_data = await req.json(); const request_data = await req.json();
try { try {
@ -43,7 +81,7 @@ async function handle(
return NextResponse.json({ status: 1 }); return NextResponse.json({ status: 1 });
} }
// export const GET = handle; export const GET = handle;
export const POST = handle; export const POST = handle;
// export const runtime = "edge"; // export const runtime = "edge";

View File

@ -101,7 +101,7 @@ import { getClientConfig } from "../config/client";
import Image from "next/image"; import Image from "next/image";
import { useAllModels } from "../utils/hooks"; import { useAllModels } from "../utils/hooks";
import { MultimodalContent } from "../client/api"; import { MultimodalContent } from "../client/api";
import { getTokenLength } from "@/lib/utils"; // import { getTokenLength } from "@/lib/utils";
import VoiceInput from "./voice-input"; import VoiceInput from "./voice-input";
// import GptPrompts from "./gpt-prompts"; // import GptPrompts from "./gpt-prompts";
// const VoiceInput = dynamic( // const VoiceInput = dynamic(
@ -1268,6 +1268,30 @@ function _Chat() {
setAttachImages(images); setAttachImages(images);
} }
// 加载状态结束获取token
const [loadingChange, setLoadingChange] = useState(false);
useEffect(() => {
if (!isLoading && loadingChange) {
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 {}
}
return () => {
setLoadingChange(isLoading);
};
}, [isLoading, loadingChange]);
// const [ voiceInputText, setVoiceInputText ] = useState(""); // const [ voiceInputText, setVoiceInputText ] = useState("");
// const [ voiceInputLoading, setVoiceInputLoading ] = useState(false); // const [ voiceInputLoading, setVoiceInputLoading ] = useState(false);
@ -1756,45 +1780,45 @@ function _Chat() {
); );
} }
function getCurrentDayToken(sessions: ChatSession[]): number { // function getCurrentDayToken(sessions: ChatSession[]): number {
try { // try {
const currentTime = new Date(); // const currentTime = new Date();
const startOfTheDayInTimeZone = new Date( // const startOfTheDayInTimeZone = new Date(
currentTime.getFullYear(), // currentTime.getFullYear(),
currentTime.getMonth(), // currentTime.getMonth(),
currentTime.getDate(), // currentTime.getDate(),
0, // 0,
0, // 0,
0, // 0,
); // );
const current_day_message = sessions // const current_day_message = sessions
.reduce((acc, item) => { // .reduce((acc, item) => {
// @ts-ignore // // @ts-ignore
return acc.concat(item.messages); // return acc.concat(item.messages);
}, []) // }, [])
.filter((item1) => { // .filter((item1) => {
// @ts-ignore // // @ts-ignore
const dateToCheck = new Date(item1.date); // const dateToCheck = new Date(item1.date);
return startOfTheDayInTimeZone < dateToCheck; // return startOfTheDayInTimeZone < dateToCheck;
}); // });
const all_current_day_content = current_day_message // const all_current_day_content = current_day_message
// @ts-ignore // // @ts-ignore
.map((item) => item.content) // .map((item) => item.content)
.join(" "); // .join(" ");
// 获取会话之后再整合content // // 获取会话之后再整合content
return getTokenLength(all_current_day_content); // return getTokenLength(all_current_day_content);
} catch (e) { // } catch (e) {
return 0; // return 0;
} // }
} // }
export function Chat() { export function Chat() {
const chatStore = useChatStore(); const chatStore = useChatStore();
const sessionIndex = chatStore.currentSessionIndex; const sessionIndex = chatStore.currentSessionIndex;
// 这里计先计算一下当天总token数。 // 这里计先计算一下当天总token数。
localStorage.setItem( // localStorage.setItem(
"current_day_token", // "current_day_token",
String(getCurrentDayToken(chatStore.sessions)), // String(getCurrentDayToken(chatStore.sessions)),
); // );
return <_Chat key={sessionIndex}></_Chat>; return <_Chat key={sessionIndex}></_Chat>;
} }