common.ts 4.8 KB

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