common.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. // @ts-ignore
  39. duplex: "half",
  40. signal: controller.signal,
  41. };
  42. // #1815 try to refuse gpt4 request
  43. if (DISABLE_GPT4 && req.body) {
  44. try {
  45. const clonedBody = await req.text();
  46. fetchOptions.body = clonedBody;
  47. const jsonBody = JSON.parse(clonedBody);
  48. if ((jsonBody?.model ?? "").includes("gpt-4")) {
  49. return NextResponse.json(
  50. {
  51. error: true,
  52. message: "you are not allowed to use gpt-4 model",
  53. },
  54. {
  55. status: 403,
  56. },
  57. );
  58. }
  59. } catch (e) {
  60. console.error("[OpenAI] gpt4 filter", e);
  61. }
  62. }
  63. try {
  64. const res = await fetch(fetchUrl, fetchOptions);
  65. // to prevent browser prompt for credentials
  66. const newHeaders = new Headers(res.headers);
  67. newHeaders.delete("www-authenticate");
  68. // to disable nginx buffering
  69. newHeaders.set("X-Accel-Buffering", "no");
  70. return new Response(res.body, {
  71. status: res.status,
  72. statusText: res.statusText,
  73. headers: newHeaders,
  74. });
  75. } finally {
  76. clearTimeout(timeoutId);
  77. }
  78. }