common.ts 2.6 KB

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