common.ts 4.5 KB

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