anthropic.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. ANTHROPIC_BASE_URL,
  4. Anthropic,
  5. ApiPath,
  6. DEFAULT_MODELS,
  7. ServiceProvider,
  8. ModelProvider,
  9. } from "@/app/constant";
  10. import { prettyObject } from "@/app/utils/format";
  11. import { NextRequest, NextResponse } from "next/server";
  12. import { auth } from "./auth";
  13. import { isModelAvailableInServer } from "@/app/utils/model";
  14. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  15. const ALLOWD_PATH = new Set([Anthropic.ChatPath, Anthropic.ChatPath1]);
  16. export async function handle(
  17. req: NextRequest,
  18. { params }: { params: { path: string[] } },
  19. ) {
  20. console.log("[Anthropic Route] params ", params);
  21. if (req.method === "OPTIONS") {
  22. return NextResponse.json({ body: "OK" }, { status: 200 });
  23. }
  24. const subpath = params.path.join("/");
  25. if (!ALLOWD_PATH.has(subpath)) {
  26. console.log("[Anthropic Route] forbidden path ", subpath);
  27. return NextResponse.json(
  28. {
  29. error: true,
  30. msg: "you are not allowed to request " + subpath,
  31. },
  32. {
  33. status: 403,
  34. },
  35. );
  36. }
  37. const authResult = auth(req, ModelProvider.Claude);
  38. if (authResult.error) {
  39. return NextResponse.json(authResult, {
  40. status: 401,
  41. });
  42. }
  43. try {
  44. const response = await request(req);
  45. return response;
  46. } catch (e) {
  47. console.error("[Anthropic] ", e);
  48. return NextResponse.json(prettyObject(e));
  49. }
  50. }
  51. const serverConfig = getServerSideConfig();
  52. async function request(req: NextRequest) {
  53. const controller = new AbortController();
  54. let authHeaderName = "x-api-key";
  55. let authValue =
  56. req.headers.get(authHeaderName) ||
  57. req.headers.get("Authorization")?.replaceAll("Bearer ", "").trim() ||
  58. serverConfig.anthropicApiKey ||
  59. "";
  60. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Anthropic, "");
  61. let baseUrl =
  62. serverConfig.anthropicUrl || serverConfig.baseUrl || ANTHROPIC_BASE_URL;
  63. if (!baseUrl.startsWith("http")) {
  64. baseUrl = `https://${baseUrl}`;
  65. }
  66. if (baseUrl.endsWith("/")) {
  67. baseUrl = baseUrl.slice(0, -1);
  68. }
  69. console.log("[Proxy] ", path);
  70. console.log("[Base Url]", baseUrl);
  71. const timeoutId = setTimeout(
  72. () => {
  73. controller.abort();
  74. },
  75. 10 * 60 * 1000,
  76. );
  77. // try rebuild url, when using cloudflare ai gateway in server
  78. const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}${path}`);
  79. const fetchOptions: RequestInit = {
  80. headers: {
  81. "Content-Type": "application/json",
  82. "Cache-Control": "no-store",
  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. isModelAvailableInServer(
  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. }