alibaba.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. ALIBABA_BASE_URL,
  4. ApiPath,
  5. ModelProvider,
  6. ServiceProvider,
  7. } from "@/app/constant";
  8. import { prettyObject } from "@/app/utils/format";
  9. import { NextRequest, NextResponse } from "next/server";
  10. import { auth } from "@/app/api/auth";
  11. import { isModelAvailableInServer } from "@/app/utils/model";
  12. const serverConfig = getServerSideConfig();
  13. export async function handle(
  14. req: NextRequest,
  15. { params }: { params: { path: string[] } },
  16. ) {
  17. console.log("[Alibaba Route] params ", params);
  18. if (req.method === "OPTIONS") {
  19. return NextResponse.json({ body: "OK" }, { status: 200 });
  20. }
  21. const authResult = auth(req, ModelProvider.Qwen);
  22. if (authResult.error) {
  23. return NextResponse.json(authResult, {
  24. status: 401,
  25. });
  26. }
  27. try {
  28. const response = await request(req);
  29. return response;
  30. } catch (e) {
  31. console.error("[Alibaba] ", e);
  32. return NextResponse.json(prettyObject(e));
  33. }
  34. }
  35. async function request(req: NextRequest) {
  36. const controller = new AbortController();
  37. // alibaba use base url or just remove the path
  38. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Alibaba, "");
  39. let baseUrl = serverConfig.alibabaUrl || ALIBABA_BASE_URL;
  40. if (!baseUrl.startsWith("http")) {
  41. baseUrl = `https://${baseUrl}`;
  42. }
  43. if (baseUrl.endsWith("/")) {
  44. baseUrl = baseUrl.slice(0, -1);
  45. }
  46. console.log("[Proxy] ", path);
  47. console.log("[Base Url]", baseUrl);
  48. const timeoutId = setTimeout(
  49. () => {
  50. controller.abort();
  51. },
  52. 10 * 60 * 1000,
  53. );
  54. const fetchUrl = `${baseUrl}${path}`;
  55. const fetchOptions: RequestInit = {
  56. headers: {
  57. "Content-Type": "application/json",
  58. Authorization: req.headers.get("Authorization") ?? "",
  59. "X-DashScope-SSE": req.headers.get("X-DashScope-SSE") ?? "disable",
  60. },
  61. method: req.method,
  62. body: req.body,
  63. redirect: "manual",
  64. // @ts-ignore
  65. duplex: "half",
  66. signal: controller.signal,
  67. };
  68. // #1815 try to refuse some request to some models
  69. if (serverConfig.customModels && req.body) {
  70. try {
  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 (
  76. isModelAvailableInServer(
  77. serverConfig.customModels,
  78. jsonBody?.model as string,
  79. ServiceProvider.Alibaba as string,
  80. )
  81. ) {
  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(`[Alibaba] filter`, e);
  94. }
  95. }
  96. try {
  97. const res = await fetch(fetchUrl, fetchOptions);
  98. // to prevent browser prompt for credentials
  99. const newHeaders = new Headers(res.headers);
  100. newHeaders.delete("www-authenticate");
  101. // to disable nginx buffering
  102. newHeaders.set("X-Accel-Buffering", "no");
  103. return new Response(res.body, {
  104. status: res.status,
  105. statusText: res.statusText,
  106. headers: newHeaders,
  107. });
  108. } finally {
  109. clearTimeout(timeoutId);
  110. }
  111. }