common.ts 5.7 KB

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