common.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. // this fix [Org ID] undefined in server side if not using custom point
  38. if (serverConfig.openaiOrgId !== undefined) {
  39. console.log("[Org ID]", serverConfig.openaiOrgId);
  40. }
  41. const timeoutId = setTimeout(
  42. () => {
  43. controller.abort();
  44. },
  45. 10 * 60 * 1000,
  46. );
  47. if (serverConfig.isAzure) {
  48. if (!serverConfig.azureApiVersion) {
  49. return NextResponse.json({
  50. error: true,
  51. message: `missing AZURE_API_VERSION in server env vars`,
  52. });
  53. }
  54. path = makeAzurePath(path, serverConfig.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 modelTable = collectModelTable(
  78. DEFAULT_MODELS,
  79. serverConfig.customModels,
  80. );
  81. const clonedBody = await req.text();
  82. fetchOptions.body = clonedBody;
  83. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  84. // not undefined and is false
  85. if (modelTable[jsonBody?.model ?? ""].available === false) {
  86. return NextResponse.json(
  87. {
  88. error: true,
  89. message: `you are not allowed to use ${jsonBody?.model} model`,
  90. },
  91. {
  92. status: 403,
  93. },
  94. );
  95. }
  96. } catch (e) {
  97. console.error("[OpenAI] gpt4 filter", e);
  98. }
  99. }
  100. try {
  101. const res = await fetch(fetchUrl, fetchOptions);
  102. // to prevent browser prompt for credentials
  103. const newHeaders = new Headers(res.headers);
  104. newHeaders.delete("www-authenticate");
  105. // to disable nginx buffering
  106. newHeaders.set("X-Accel-Buffering", "no");
  107. // The latest version of the OpenAI API forced the content-encoding to be "br" in json response
  108. // So if the streaming is disabled, we need to remove the content-encoding header
  109. // Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header
  110. // The browser will try to decode the response with brotli and fail
  111. newHeaders.delete("content-encoding");
  112. return new Response(res.body, {
  113. status: res.status,
  114. statusText: res.statusText,
  115. headers: newHeaders,
  116. });
  117. } finally {
  118. clearTimeout(timeoutId);
  119. }
  120. }