common.ts 4.8 KB

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