anthropic.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. ANTHROPIC_BASE_URL,
  4. Anthropic,
  5. ApiPath,
  6. ServiceProvider,
  7. ModelProvider,
  8. } from "@/app/constant";
  9. import { prettyObject } from "@/app/utils/format";
  10. import { NextRequest, NextResponse } from "next/server";
  11. import { auth } from "./auth";
  12. import { isModelNotavailableInServer } from "@/app/utils/model";
  13. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  14. const ALLOWD_PATH = new Set([Anthropic.ChatPath, Anthropic.ChatPath1]);
  15. export async function handle(
  16. req: NextRequest,
  17. { params }: { params: { path: string[] } },
  18. ) {
  19. console.log("[Anthropic Route] params ", params);
  20. if (req.method === "OPTIONS") {
  21. return NextResponse.json({ body: "OK" }, { status: 200 });
  22. }
  23. const subpath = params.path.join("/");
  24. if (!ALLOWD_PATH.has(subpath)) {
  25. console.log("[Anthropic Route] forbidden path ", subpath);
  26. return NextResponse.json(
  27. {
  28. error: true,
  29. msg: "you are not allowed to request " + subpath,
  30. },
  31. {
  32. status: 403,
  33. },
  34. );
  35. }
  36. const authResult = auth(req, ModelProvider.Claude);
  37. if (authResult.error) {
  38. return NextResponse.json(authResult, {
  39. status: 401,
  40. });
  41. }
  42. try {
  43. const response = await request(req);
  44. return response;
  45. } catch (e) {
  46. console.error("[Anthropic] ", e);
  47. return NextResponse.json(prettyObject(e));
  48. }
  49. }
  50. const serverConfig = getServerSideConfig();
  51. async function request(req: NextRequest) {
  52. const controller = new AbortController();
  53. let authHeaderName = "x-api-key";
  54. let authValue =
  55. req.headers.get(authHeaderName) ||
  56. req.headers.get("Authorization")?.replaceAll("Bearer ", "").trim() ||
  57. serverConfig.anthropicApiKey ||
  58. "";
  59. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Anthropic, "");
  60. let baseUrl =
  61. serverConfig.anthropicUrl || serverConfig.baseUrl || ANTHROPIC_BASE_URL;
  62. if (!baseUrl.startsWith("http")) {
  63. baseUrl = `https://${baseUrl}`;
  64. }
  65. if (baseUrl.endsWith("/")) {
  66. baseUrl = baseUrl.slice(0, -1);
  67. }
  68. console.log("[Proxy] ", path);
  69. console.log("[Base Url]", baseUrl);
  70. const timeoutId = setTimeout(
  71. () => {
  72. controller.abort();
  73. },
  74. 10 * 60 * 1000,
  75. );
  76. // try rebuild url, when using cloudflare ai gateway in server
  77. const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}${path}`);
  78. const fetchOptions: RequestInit = {
  79. headers: {
  80. "Content-Type": "application/json",
  81. "Cache-Control": "no-store",
  82. "anthropic-dangerous-direct-browser-access": "true",
  83. [authHeaderName]: authValue,
  84. "anthropic-version":
  85. req.headers.get("anthropic-version") ||
  86. serverConfig.anthropicApiVersion ||
  87. Anthropic.Vision,
  88. },
  89. method: req.method,
  90. body: req.body,
  91. redirect: "manual",
  92. // @ts-ignore
  93. duplex: "half",
  94. signal: controller.signal,
  95. };
  96. // #1815 try to refuse some request to some models
  97. if (serverConfig.customModels && req.body) {
  98. try {
  99. const clonedBody = await req.text();
  100. fetchOptions.body = clonedBody;
  101. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  102. // not undefined and is false
  103. if (
  104. isModelNotavailableInServer(
  105. serverConfig.customModels,
  106. jsonBody?.model as string,
  107. ServiceProvider.Anthropic as string,
  108. )
  109. ) {
  110. return NextResponse.json(
  111. {
  112. error: true,
  113. message: `you are not allowed to use ${jsonBody?.model} model`,
  114. },
  115. {
  116. status: 403,
  117. },
  118. );
  119. }
  120. } catch (e) {
  121. console.error(`[Anthropic] filter`, e);
  122. }
  123. }
  124. // console.log("[Anthropic request]", fetchOptions.headers, req.method);
  125. try {
  126. const res = await fetch(fetchUrl, fetchOptions);
  127. // console.log(
  128. // "[Anthropic response]",
  129. // res.status,
  130. // " ",
  131. // res.headers,
  132. // res.url,
  133. // );
  134. // to prevent browser prompt for credentials
  135. const newHeaders = new Headers(res.headers);
  136. newHeaders.delete("www-authenticate");
  137. // to disable nginx buffering
  138. newHeaders.set("X-Accel-Buffering", "no");
  139. return new Response(res.body, {
  140. status: res.status,
  141. statusText: res.statusText,
  142. headers: newHeaders,
  143. });
  144. } finally {
  145. clearTimeout(timeoutId);
  146. }
  147. }