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