common.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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. if (serverConfig.isAzure) {
  10. const authValue =
  11. req.headers
  12. .get("Authorization")
  13. ?.trim()
  14. .replaceAll("Bearer ", "")
  15. .trim() ?? "";
  16. } else {
  17. const authValue = req.headers.get("Authorization") ?? "";
  18. }
  19. const authHeaderName = serverConfig.isAzure ? "api-key" : "Authorization";
  20. let path = `${req.nextUrl.pathname}${req.nextUrl.search}`.replaceAll(
  21. "/api/openai/",
  22. "",
  23. );
  24. let baseUrl =
  25. serverConfig.azureUrl || serverConfig.baseUrl || OPENAI_BASE_URL;
  26. if (!baseUrl.startsWith("http")) {
  27. baseUrl = `https://${baseUrl}`;
  28. }
  29. if (baseUrl.endsWith("/")) {
  30. baseUrl = baseUrl.slice(0, -1);
  31. }
  32. console.log("[Proxy] ", path);
  33. console.log("[Base Url]", baseUrl);
  34. // this fix [Org ID] undefined in server side if not using custom point
  35. if (serverConfig.openaiOrgId !== undefined) {
  36. console.log("[Org ID]", serverConfig.openaiOrgId);
  37. }
  38. const timeoutId = setTimeout(
  39. () => {
  40. controller.abort();
  41. },
  42. 10 * 60 * 1000,
  43. );
  44. if (serverConfig.isAzure) {
  45. if (!serverConfig.azureApiVersion) {
  46. return NextResponse.json({
  47. error: true,
  48. message: `missing AZURE_API_VERSION in server env vars`,
  49. });
  50. }
  51. path = makeAzurePath(path, serverConfig.azureApiVersion);
  52. }
  53. const fetchUrl = `${baseUrl}/${path}`;
  54. const fetchOptions: RequestInit = {
  55. headers: {
  56. "Content-Type": "application/json",
  57. "Cache-Control": "no-store",
  58. [authHeaderName]: authValue,
  59. ...(serverConfig.openaiOrgId && {
  60. "OpenAI-Organization": serverConfig.openaiOrgId,
  61. }),
  62. },
  63. method: req.method,
  64. body: req.body,
  65. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  66. redirect: "manual",
  67. // @ts-ignore
  68. duplex: "half",
  69. signal: controller.signal,
  70. };
  71. // #1815 try to refuse gpt4 request
  72. if (serverConfig.customModels && req.body) {
  73. try {
  74. const modelTable = collectModelTable(
  75. DEFAULT_MODELS,
  76. serverConfig.customModels,
  77. );
  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 (modelTable[jsonBody?.model ?? ""].available === false) {
  83. return NextResponse.json(
  84. {
  85. error: true,
  86. message: `you are not allowed to use ${jsonBody?.model} model`,
  87. },
  88. {
  89. status: 403,
  90. },
  91. );
  92. }
  93. } catch (e) {
  94. console.error("[OpenAI] gpt4 filter", e);
  95. }
  96. }
  97. try {
  98. const res = await fetch(fetchUrl, fetchOptions);
  99. // to prevent browser prompt for credentials
  100. const newHeaders = new Headers(res.headers);
  101. newHeaders.delete("www-authenticate");
  102. // to disable nginx buffering
  103. newHeaders.set("X-Accel-Buffering", "no");
  104. return new Response(res.body, {
  105. status: res.status,
  106. statusText: res.statusText,
  107. headers: newHeaders,
  108. });
  109. } finally {
  110. clearTimeout(timeoutId);
  111. }
  112. }