common.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { NextRequest, NextResponse } from "next/server";
  2. export 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. const DISABLE_GPT4 = !!process.env.DISABLE_GPT4;
  7. export async function requestOpenai(req: NextRequest) {
  8. const controller = new AbortController();
  9. const authValue = req.headers.get("Authorization") ?? "";
  10. const openaiPath = `${req.nextUrl.pathname}${req.nextUrl.search}`.replaceAll(
  11. "/api/openai/",
  12. "",
  13. );
  14. let baseUrl = BASE_URL;
  15. if (!baseUrl.startsWith("http")) {
  16. baseUrl = `${PROTOCOL}://${baseUrl}`;
  17. }
  18. console.log("[Proxy] ", openaiPath);
  19. console.log("[Base Url]", baseUrl);
  20. if (process.env.OPENAI_ORG_ID) {
  21. console.log("[Org ID]", process.env.OPENAI_ORG_ID);
  22. }
  23. const timeoutId = setTimeout(() => {
  24. controller.abort();
  25. }, 10 * 60 * 1000);
  26. const fetchUrl = `${baseUrl}/${openaiPath}`;
  27. const fetchOptions: RequestInit = {
  28. headers: {
  29. "Content-Type": "application/json",
  30. "Cache-Control": "no-store",
  31. Authorization: authValue,
  32. ...(process.env.OPENAI_ORG_ID && {
  33. "OpenAI-Organization": process.env.OPENAI_ORG_ID,
  34. }),
  35. },
  36. method: req.method,
  37. body: req.body,
  38. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  39. redirect: "manual",
  40. // @ts-ignore
  41. duplex: "half",
  42. signal: controller.signal,
  43. };
  44. // #1815 try to refuse gpt4 request
  45. if (DISABLE_GPT4 && req.body) {
  46. try {
  47. const clonedBody = await req.text();
  48. fetchOptions.body = clonedBody;
  49. const jsonBody = JSON.parse(clonedBody);
  50. if ((jsonBody?.model ?? "").includes("gpt-4")) {
  51. return NextResponse.json(
  52. {
  53. error: true,
  54. message: "you are not allowed to use gpt-4 model",
  55. },
  56. {
  57. status: 403,
  58. },
  59. );
  60. }
  61. } catch (e) {
  62. console.error("[OpenAI] gpt4 filter", e);
  63. }
  64. }
  65. try {
  66. const res = await fetch(fetchUrl, fetchOptions);
  67. // to prevent browser prompt for credentials
  68. const newHeaders = new Headers(res.headers);
  69. newHeaders.delete("www-authenticate");
  70. // to disable nginx buffering
  71. newHeaders.set("X-Accel-Buffering", "no");
  72. return new Response(res.body, {
  73. status: res.status,
  74. statusText: res.statusText,
  75. headers: newHeaders,
  76. });
  77. } finally {
  78. clearTimeout(timeoutId);
  79. }
  80. }