common.ts 4.8 KB

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