diff --git a/app/api/credit-summary/route.ts b/app/api/credit-summary/route.ts new file mode 100644 index 000000000..6c7c3c399 --- /dev/null +++ b/app/api/credit-summary/route.ts @@ -0,0 +1,22 @@ +import { NextRequest } from "next/server"; +export async function POST(req: NextRequest) { + try { + let apiKey = process.env.OPENAI_API_KEY; + const userApiKey = req.headers.get("token"); + if (userApiKey) { + apiKey = userApiKey; + } + + const res = await fetch("https://api.openai.com/dashboard/billing/credit_grants", { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${apiKey}`, + }, + method: "GET" + }); + console.log(res.body) + return new Response(res.body); + } catch (error) { + console.error("[TOKEN]", error); + } + } \ No newline at end of file diff --git a/app/components/settings.tsx b/app/components/settings.tsx index 241cebae6..baf3c8fdc 100644 --- a/app/components/settings.tsx +++ b/app/components/settings.tsx @@ -27,6 +27,7 @@ import { getCurrentCommitId } from "../utils"; import Link from "next/link"; import { UPDATE_URL } from "../constant"; import { SearchService, usePromptStore } from "../store/prompt"; +import { requestAccountBalance, requestCreditSummary, requestWithPrompt } from "../requests"; function SettingItem(props: { title: string; @@ -72,6 +73,7 @@ export function Settings(props: { closeSettings: () => void }) { useEffect(() => { checkUpdate(); + requestAccountBalance().then((res)=> setAccountBalance(res)) }, []); const accessStore = useAccessStore(); @@ -84,6 +86,8 @@ export function Settings(props: { closeSettings: () => void }) { const builtinCount = SearchService.count.builtin; const customCount = promptStore.prompts.size ?? 0; + const [accountBalance, setAccountBalance] = useState(-1); + return ( <>
@@ -320,10 +324,24 @@ export function Settings(props: { closeSettings: () => void }) { placeholder={Locale.Settings.Token.Placeholder} onChange={(e) => { accessStore.updateToken(e.currentTarget.value); + requestAccountBalance().then((res)=> setAccountBalance(res)) }} > + + + + 0) { headers["token"] = accessStore.token; } - + return headers; } @@ -57,6 +57,22 @@ export async function requestChat(messages: Message[]) { return (await res.json()) as ChatReponse; } +export async function requestCreditSummary() { + const res = await fetch("/api/credit-summary", { + method: "POST", + headers: { + "Content-Type": "application/json", + ...getHeaders(), + }, + }); + return (await res.json()) +} + +export async function requestAccountBalance() { + const res = await requestCreditSummary(); + return res?.total_available ?? -1 +} + export async function requestChatStream( messages: Message[], options?: {