common.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { getServerSideConfig } from "../config/server";
  3. import { DEFAULT_MODELS, OPENAI_BASE_URL, GEMINI_BASE_URL } from "../constant";
  4. import { isModelAvailableInServer } from "../utils/model";
  5. import { makeAzurePath } from "../azure";
  6. const serverConfig = getServerSideConfig();
  7. export async function requestOpenai(req: NextRequest) {
  8. const controller = new AbortController();
  9. var authValue,
  10. authHeaderName = "";
  11. if (serverConfig.isAzure) {
  12. authValue =
  13. req.headers
  14. .get("Authorization")
  15. ?.trim()
  16. .replaceAll("Bearer ", "")
  17. .trim() ?? "";
  18. authHeaderName = "api-key";
  19. } else {
  20. authValue = req.headers.get("Authorization") ?? "";
  21. authHeaderName = "Authorization";
  22. }
  23. let path = `${req.nextUrl.pathname}${req.nextUrl.search}`.replaceAll(
  24. "/api/openai/",
  25. "",
  26. );
  27. let baseUrl =
  28. serverConfig.azureUrl || serverConfig.baseUrl || OPENAI_BASE_URL;
  29. if (!baseUrl.startsWith("http")) {
  30. baseUrl = `https://${baseUrl}`;
  31. }
  32. if (baseUrl.endsWith("/")) {
  33. baseUrl = baseUrl.slice(0, -1);
  34. }
  35. console.log("[Proxy] ", path);
  36. console.log("[Base Url]", baseUrl);
  37. const timeoutId = setTimeout(
  38. () => {
  39. controller.abort();
  40. },
  41. 10 * 60 * 1000,
  42. );
  43. if (serverConfig.isAzure) {
  44. if (!serverConfig.azureApiVersion) {
  45. return NextResponse.json({
  46. error: true,
  47. message: `missing AZURE_API_VERSION in server env vars`,
  48. });
  49. }
  50. path = makeAzurePath(path, serverConfig.azureApiVersion);
  51. }
  52. const fetchUrl = `${baseUrl}/${path}`;
  53. const fetchOptions: RequestInit = {
  54. headers: {
  55. "Content-Type": "application/json",
  56. "Cache-Control": "no-store",
  57. [authHeaderName]: authValue,
  58. ...(serverConfig.openaiOrgId && {
  59. "OpenAI-Organization": serverConfig.openaiOrgId,
  60. }),
  61. },
  62. method: req.method,
  63. body: req.body,
  64. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  65. redirect: "manual",
  66. // @ts-ignore
  67. duplex: "half",
  68. signal: controller.signal,
  69. };
  70. // #1815 try to refuse gpt4 request
  71. if (serverConfig.customModels && req.body) {
  72. try {
  73. const clonedBody = await req.text();
  74. fetchOptions.body = clonedBody;
  75. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  76. // not undefined and is false
  77. if (
  78. isModelAvailableInServer(serverConfig.customModels, jsonBody?.model)
  79. ) {
  80. return NextResponse.json(
  81. {
  82. error: true,
  83. message: `you are not allowed to use ${jsonBody?.model} model`,
  84. },
  85. {
  86. status: 403,
  87. },
  88. );
  89. }
  90. } catch (e) {
  91. console.error("[OpenAI] gpt4 filter", e);
  92. }
  93. }
  94. try {
  95. const res = await fetch(fetchUrl, fetchOptions);
  96. // Extract the OpenAI-Organization header from the response
  97. const openaiOrganizationHeader = res.headers.get("OpenAI-Organization");
  98. // Check if serverConfig.openaiOrgId is defined and not an empty string
  99. if (serverConfig.openaiOrgId && serverConfig.openaiOrgId.trim() !== "") {
  100. // If openaiOrganizationHeader is present, log it; otherwise, log that the header is not present
  101. console.log("[Org ID]", openaiOrganizationHeader);
  102. } else {
  103. console.log("[Org ID] is not set up.");
  104. }
  105. // to prevent browser prompt for credentials
  106. const newHeaders = new Headers(res.headers);
  107. newHeaders.delete("www-authenticate");
  108. // to disable nginx buffering
  109. newHeaders.set("X-Accel-Buffering", "no");
  110. // Conditionally delete the OpenAI-Organization header from the response if [Org ID] is undefined or empty (not setup in ENV)
  111. // Also, this is to prevent the header from being sent to the client
  112. if (!serverConfig.openaiOrgId || serverConfig.openaiOrgId.trim() === "") {
  113. newHeaders.delete("OpenAI-Organization");
  114. }
  115. // The latest version of the OpenAI API forced the content-encoding to be "br" in json response
  116. // So if the streaming is disabled, we need to remove the content-encoding header
  117. // Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header
  118. // The browser will try to decode the response with brotli and fail
  119. newHeaders.delete("content-encoding");
  120. return new Response(res.body, {
  121. status: res.status,
  122. statusText: res.statusText,
  123. headers: newHeaders,
  124. });
  125. } finally {
  126. clearTimeout(timeoutId);
  127. }
  128. }