common.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { NextRequest } from "next/server";
  2. const OPENAI_URL = "api.openai.com";
  3. const DEFAULT_PROTOCOL = "https";
  4. const PROTOCOL = process.env.PROTOCOL ?? DEFAULT_PROTOCOL;
  5. const BASE_URL = process.env.BASE_URL ?? OPENAI_URL;
  6. export async function requestOpenai(req: NextRequest) {
  7. const authValue = req.headers.get("Authorization") ?? "";
  8. const openaiPath = `${req.nextUrl.pathname}${req.nextUrl.search}`.replaceAll(
  9. "/api/openai/",
  10. "",
  11. );
  12. let baseUrl = BASE_URL;
  13. if (!baseUrl.startsWith("http")) {
  14. baseUrl = `${PROTOCOL}://${baseUrl}`;
  15. }
  16. console.log("[Proxy] ", openaiPath);
  17. console.log("[Base Url]", baseUrl);
  18. if (process.env.OPENAI_ORG_ID) {
  19. console.log("[Org ID]", process.env.OPENAI_ORG_ID);
  20. }
  21. if (!authValue || !authValue.startsWith("Bearer sk-")) {
  22. console.error("[OpenAI Request] invalid api key provided", authValue);
  23. }
  24. return fetch(`${baseUrl}/${openaiPath}`, {
  25. headers: {
  26. "Content-Type": "application/json",
  27. Authorization: authValue,
  28. ...(process.env.OPENAI_ORG_ID && {
  29. "OpenAI-Organization": process.env.OPENAI_ORG_ID,
  30. }),
  31. },
  32. cache: "no-store",
  33. method: req.method,
  34. body: req.body,
  35. });
  36. }