bytedance.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. BYTEDANCE_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("[ByteDance Route] params ", params);
  18. if (req.method === "OPTIONS") {
  19. return NextResponse.json({ body: "OK" }, { status: 200 });
  20. }
  21. const authResult = auth(req, ModelProvider.Doubao);
  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("[ByteDance] ", e);
  32. return NextResponse.json(prettyObject(e));
  33. }
  34. }
  35. async function request(req: NextRequest) {
  36. const controller = new AbortController();
  37. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.ByteDance, "");
  38. let baseUrl = serverConfig.bytedanceUrl || BYTEDANCE_BASE_URL;
  39. if (!baseUrl.startsWith("http")) {
  40. baseUrl = `https://${baseUrl}`;
  41. }
  42. if (baseUrl.endsWith("/")) {
  43. baseUrl = baseUrl.slice(0, -1);
  44. }
  45. console.log("[Proxy] ", path);
  46. console.log("[Base Url]", baseUrl);
  47. const timeoutId = setTimeout(
  48. () => {
  49. controller.abort();
  50. },
  51. 10 * 60 * 1000,
  52. );
  53. const fetchUrl = `${baseUrl}${path}`;
  54. const fetchOptions: RequestInit = {
  55. headers: {
  56. "Content-Type": "application/json",
  57. Authorization: req.headers.get("Authorization") ?? "",
  58. },
  59. method: req.method,
  60. body: req.body,
  61. redirect: "manual",
  62. // @ts-ignore
  63. duplex: "half",
  64. signal: controller.signal,
  65. };
  66. // #1815 try to refuse some request to some models
  67. if (serverConfig.customModels && req.body) {
  68. try {
  69. const clonedBody = await req.text();
  70. fetchOptions.body = clonedBody;
  71. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  72. // not undefined and is false
  73. if (
  74. isModelAvailableInServer(
  75. serverConfig.customModels,
  76. jsonBody?.model as string,
  77. ServiceProvider.ByteDance as string,
  78. )
  79. ) {
  80. return NextResponse.json(
  81. {
  82. error: true,
  83. message: `you are not allowed to use ${jsonBody?.model} model`,
  84. },
  85. {
  86. status: 403,
  87. },
  88. );
  89. }
  90. } catch (e) {
  91. console.error(`[ByteDance] filter`, e);
  92. }
  93. }
  94. try {
  95. const res = await fetch(fetchUrl, fetchOptions);
  96. // to prevent browser prompt for credentials
  97. const newHeaders = new Headers(res.headers);
  98. newHeaders.delete("www-authenticate");
  99. // to disable nginx buffering
  100. newHeaders.set("X-Accel-Buffering", "no");
  101. return new Response(res.body, {
  102. status: res.status,
  103. statusText: res.statusText,
  104. headers: newHeaders,
  105. });
  106. } finally {
  107. clearTimeout(timeoutId);
  108. }
  109. }