common.ts 3.3 KB

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