(req: NextRequest)
| 14 | }; |
| 15 | |
| 16 | const handler = async (req: NextRequest) => { |
| 17 | const reqBody = await req.json(); |
| 18 | const apiKey = req.headers.get("x-openai-key") || openAIApiKey; |
| 19 | |
| 20 | if (!apiKey) { |
| 21 | return new Response( |
| 22 | JSON.stringify({ |
| 23 | error: { |
| 24 | message: "OpenAI API Key is missing. You can supply your own key via [Setting](/setting).", |
| 25 | }, |
| 26 | }), |
| 27 | { |
| 28 | headers: { |
| 29 | "Content-Type": "application/json", |
| 30 | }, |
| 31 | status: 401, |
| 32 | } |
| 33 | ); |
| 34 | } |
| 35 | |
| 36 | const useServerKey = !req.headers.get("x-openai-key"); |
| 37 | const sessionToken = req.cookies.get("next-auth.session-token")?.value; |
| 38 | const currentUrl = new URL(req.url); |
| 39 | const usageUrl = new URL(currentUrl.protocol + "//" + currentUrl.host + "/api/usage"); |
| 40 | const requestHeaders: any = { |
| 41 | Authorization: `Bearer ${sessionToken}`, |
| 42 | }; |
| 43 | if (req.headers.get("x-openai-model")) { |
| 44 | // Pass model to usage API to calculate usage |
| 45 | requestHeaders["x-openai-model"] = req.headers.get("x-openai-model"); |
| 46 | } |
| 47 | |
| 48 | if (useServerKey) { |
| 49 | if (hasFeature("account") && !sessionToken) { |
| 50 | return new Response( |
| 51 | JSON.stringify({ |
| 52 | error: { |
| 53 | message: "Please sign up to get free quota.", |
| 54 | }, |
| 55 | }), |
| 56 | { |
| 57 | headers: { |
| 58 | "Content-Type": "application/json", |
| 59 | }, |
| 60 | status: 401, |
| 61 | } |
| 62 | ); |
| 63 | } |
| 64 | |
| 65 | if (hasFeature("quota")) { |
| 66 | const usageRes = await fetch(usageUrl, { |
| 67 | method: "GET", |
| 68 | headers: requestHeaders, |
| 69 | }); |
| 70 | if (!usageRes.ok) { |
| 71 | return new Response(usageRes.body, { |
| 72 | status: 500, |
| 73 | statusText: usageRes.statusText, |
nothing calls this directly
no test coverage detected