moonshot.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. Moonshot,
  4. MOONSHOT_BASE_URL,
  5. ApiPath,
  6. ModelProvider,
  7. ServiceProvider,
  8. } from "@/app/constant";
  9. import { prettyObject } from "@/app/utils/format";
  10. import { NextRequest, NextResponse } from "next/server";
  11. import { auth } from "@/app/api/auth";
  12. import { isModelAvailableInServer } from "@/app/utils/model";
  13. import type { RequestPayload } from "@/app/client/platforms/openai";
  14. const serverConfig = getServerSideConfig();
  15. export async function handle(
  16. req: NextRequest,
  17. { params }: { params: { path: string[] } },
  18. ) {
  19. console.log("[Moonshot Route] params ", params);
  20. if (req.method === "OPTIONS") {
  21. return NextResponse.json({ body: "OK" }, { status: 200 });
  22. }
  23. const authResult = auth(req, ModelProvider.Moonshot);
  24. if (authResult.error) {
  25. return NextResponse.json(authResult, {
  26. status: 401,
  27. });
  28. }
  29. try {
  30. const response = await request(req);
  31. return response;
  32. } catch (e) {
  33. console.error("[Moonshot] ", e);
  34. return NextResponse.json(prettyObject(e));
  35. }
  36. }
  37. async function request(req: NextRequest) {
  38. const controller = new AbortController();
  39. // alibaba use base url or just remove the path
  40. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Moonshot, "");
  41. let baseUrl = serverConfig.moonshotUrl || MOONSHOT_BASE_URL;
  42. if (!baseUrl.startsWith("http")) {
  43. baseUrl = `https://${baseUrl}`;
  44. }
  45. if (baseUrl.endsWith("/")) {
  46. baseUrl = baseUrl.slice(0, -1);
  47. }
  48. console.log("[Proxy] ", path);
  49. console.log("[Base Url]", baseUrl);
  50. const timeoutId = setTimeout(
  51. () => {
  52. controller.abort();
  53. },
  54. 10 * 60 * 1000,
  55. );
  56. const fetchUrl = `${baseUrl}${path}`;
  57. const fetchOptions: RequestInit = {
  58. headers: {
  59. "Content-Type": "application/json",
  60. Authorization: req.headers.get("Authorization") ?? "",
  61. },
  62. method: req.method,
  63. body: req.body,
  64. redirect: "manual",
  65. // @ts-ignore
  66. duplex: "half",
  67. signal: controller.signal,
  68. };
  69. // #1815 try to refuse some request to some models
  70. if (serverConfig.customModels && req.body) {
  71. try {
  72. const clonedBody = await req.text();
  73. fetchOptions.body = clonedBody;
  74. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  75. // not undefined and is false
  76. if (
  77. isModelAvailableInServer(
  78. serverConfig.customModels,
  79. jsonBody?.model as string,
  80. ServiceProvider.Moonshot as string,
  81. )
  82. ) {
  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(`[Moonshot] 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. }