baidu.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. BAIDU_BASE_URL,
  4. ApiPath,
  5. ModelProvider,
  6. BAIDU_OATUH_URL,
  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 { getAccessToken } from "@/app/utils/baidu";
  14. const serverConfig = getServerSideConfig();
  15. export async function handle(
  16. req: NextRequest,
  17. { params }: { params: { path: string[] } },
  18. ) {
  19. console.log("[Baidu Route] params ", params);
  20. if (req.method === "OPTIONS") {
  21. return NextResponse.json({ body: "OK" }, { status: 200 });
  22. }
  23. const authResult = auth(req, ModelProvider.Ernie);
  24. if (authResult.error) {
  25. return NextResponse.json(authResult, {
  26. status: 401,
  27. });
  28. }
  29. if (!serverConfig.baiduApiKey || !serverConfig.baiduSecretKey) {
  30. return NextResponse.json(
  31. {
  32. error: true,
  33. message: `missing BAIDU_API_KEY or BAIDU_SECRET_KEY in server env vars`,
  34. },
  35. {
  36. status: 401,
  37. },
  38. );
  39. }
  40. try {
  41. const response = await request(req);
  42. return response;
  43. } catch (e) {
  44. console.error("[Baidu] ", e);
  45. return NextResponse.json(prettyObject(e));
  46. }
  47. }
  48. async function request(req: NextRequest) {
  49. const controller = new AbortController();
  50. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Baidu, "");
  51. let baseUrl = serverConfig.baiduUrl || BAIDU_BASE_URL;
  52. if (!baseUrl.startsWith("http")) {
  53. baseUrl = `https://${baseUrl}`;
  54. }
  55. if (baseUrl.endsWith("/")) {
  56. baseUrl = baseUrl.slice(0, -1);
  57. }
  58. console.log("[Proxy] ", path);
  59. console.log("[Base Url]", baseUrl);
  60. const timeoutId = setTimeout(
  61. () => {
  62. controller.abort();
  63. },
  64. 10 * 60 * 1000,
  65. );
  66. const { access_token } = await getAccessToken(
  67. serverConfig.baiduApiKey as string,
  68. serverConfig.baiduSecretKey as string,
  69. );
  70. const fetchUrl = `${baseUrl}${path}?access_token=${access_token}`;
  71. const fetchOptions: RequestInit = {
  72. headers: {
  73. "Content-Type": "application/json",
  74. },
  75. method: req.method,
  76. body: req.body,
  77. redirect: "manual",
  78. // @ts-ignore
  79. duplex: "half",
  80. signal: controller.signal,
  81. };
  82. // #1815 try to refuse some request to some models
  83. if (serverConfig.customModels && req.body) {
  84. try {
  85. const clonedBody = await req.text();
  86. fetchOptions.body = clonedBody;
  87. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  88. // not undefined and is false
  89. if (
  90. isModelAvailableInServer(
  91. serverConfig.customModels,
  92. jsonBody?.model as string,
  93. ServiceProvider.Baidu as string,
  94. )
  95. ) {
  96. return NextResponse.json(
  97. {
  98. error: true,
  99. message: `you are not allowed to use ${jsonBody?.model} model`,
  100. },
  101. {
  102. status: 403,
  103. },
  104. );
  105. }
  106. } catch (e) {
  107. console.error(`[Baidu] filter`, e);
  108. }
  109. }
  110. try {
  111. const res = await fetch(fetchUrl, fetchOptions);
  112. // to prevent browser prompt for credentials
  113. const newHeaders = new Headers(res.headers);
  114. newHeaders.delete("www-authenticate");
  115. // to disable nginx buffering
  116. newHeaders.set("X-Accel-Buffering", "no");
  117. return new Response(res.body, {
  118. status: res.status,
  119. statusText: res.statusText,
  120. headers: newHeaders,
  121. });
  122. } finally {
  123. clearTimeout(timeoutId);
  124. }
  125. }