common.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 && serverConfig.azureUrl) {
  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(
  71. "deployments/",
  72. );
  73. if (deployId) {
  74. realDeployName = deployId;
  75. }
  76. }
  77. });
  78. if (realDeployName) {
  79. console.log("[Replace with DeployId", realDeployName);
  80. path = path.replaceAll(modelName, realDeployName);
  81. }
  82. }
  83. }
  84. const fetchUrl = `${baseUrl}/${path}`;
  85. const fetchOptions: RequestInit = {
  86. headers: {
  87. "Content-Type": "application/json",
  88. "Cache-Control": "no-store",
  89. [authHeaderName]: authValue,
  90. ...(serverConfig.openaiOrgId && {
  91. "OpenAI-Organization": serverConfig.openaiOrgId,
  92. }),
  93. },
  94. method: req.method,
  95. body: req.body,
  96. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  97. redirect: "manual",
  98. // @ts-ignore
  99. duplex: "half",
  100. signal: controller.signal,
  101. };
  102. // #1815 try to refuse gpt4 request
  103. if (serverConfig.customModels && req.body) {
  104. try {
  105. const clonedBody = await req.text();
  106. fetchOptions.body = clonedBody;
  107. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  108. // not undefined and is false
  109. if (
  110. isModelAvailableInServer(
  111. serverConfig.customModels,
  112. jsonBody?.model as string,
  113. ServiceProvider.OpenAI as string,
  114. ) ||
  115. isModelAvailableInServer(
  116. serverConfig.customModels,
  117. jsonBody?.model as string,
  118. ServiceProvider.Azure as string,
  119. )
  120. ) {
  121. return NextResponse.json(
  122. {
  123. error: true,
  124. message: `you are not allowed to use ${jsonBody?.model} model`,
  125. },
  126. {
  127. status: 403,
  128. },
  129. );
  130. }
  131. } catch (e) {
  132. console.error("[OpenAI] gpt4 filter", e);
  133. }
  134. }
  135. try {
  136. const res = await fetch(fetchUrl, fetchOptions);
  137. // Extract the OpenAI-Organization header from the response
  138. const openaiOrganizationHeader = res.headers.get("OpenAI-Organization");
  139. // Check if serverConfig.openaiOrgId is defined and not an empty string
  140. if (serverConfig.openaiOrgId && serverConfig.openaiOrgId.trim() !== "") {
  141. // If openaiOrganizationHeader is present, log it; otherwise, log that the header is not present
  142. console.log("[Org ID]", openaiOrganizationHeader);
  143. } else {
  144. console.log("[Org ID] is not set up.");
  145. }
  146. // to prevent browser prompt for credentials
  147. const newHeaders = new Headers(res.headers);
  148. newHeaders.delete("www-authenticate");
  149. // to disable nginx buffering
  150. newHeaders.set("X-Accel-Buffering", "no");
  151. // Conditionally delete the OpenAI-Organization header from the response if [Org ID] is undefined or empty (not setup in ENV)
  152. // Also, this is to prevent the header from being sent to the client
  153. if (!serverConfig.openaiOrgId || serverConfig.openaiOrgId.trim() === "") {
  154. newHeaders.delete("OpenAI-Organization");
  155. }
  156. // The latest version of the OpenAI API forced the content-encoding to be "br" in json response
  157. // So if the streaming is disabled, we need to remove the content-encoding header
  158. // Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header
  159. // The browser will try to decode the response with brotli and fail
  160. newHeaders.delete("content-encoding");
  161. return new Response(res.body, {
  162. status: res.status,
  163. statusText: res.statusText,
  164. headers: newHeaders,
  165. });
  166. } finally {
  167. clearTimeout(timeoutId);
  168. }
  169. }