common.ts 5.8 KB

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