common.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. return fetch(`${baseUrl}/${openaiPath}`, {
  22. headers: {
  23. "Content-Type": "application/json",
  24. Authorization: authValue,
  25. ...(process.env.OPENAI_ORG_ID && {
  26. "OpenAI-Organization": process.env.OPENAI_ORG_ID,
  27. }),
  28. },
  29. cache: "no-store",
  30. method: req.method,
  31. body: req.body,
  32. });
  33. }