google.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { auth } from "./auth";
  3. import { getServerSideConfig } from "@/app/config/server";
  4. import { ApiPath, GEMINI_BASE_URL, ModelProvider } from "@/app/constant";
  5. import { prettyObject } from "@/app/utils/format";
  6. const serverConfig = getServerSideConfig();
  7. export async function handle(
  8. req: NextRequest,
  9. { params }: { params: { provider: string; path: string[] } },
  10. ) {
  11. console.log("[Google Route] params ", params);
  12. if (req.method === "OPTIONS") {
  13. return NextResponse.json({ body: "OK" }, { status: 200 });
  14. }
  15. const authResult = auth(req, ModelProvider.GeminiPro);
  16. if (authResult.error) {
  17. return NextResponse.json(authResult, {
  18. status: 401,
  19. });
  20. }
  21. const bearToken =
  22. req.headers.get("x-goog-api-key") || req.headers.get("Authorization") || "";
  23. const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  24. const apiKey = token ? token : serverConfig.googleApiKey;
  25. if (!apiKey) {
  26. return NextResponse.json(
  27. {
  28. error: true,
  29. message: `missing GOOGLE_API_KEY in server env vars`,
  30. },
  31. {
  32. status: 401,
  33. },
  34. );
  35. }
  36. try {
  37. const response = await request(req, apiKey);
  38. return response;
  39. } catch (e) {
  40. console.error("[Google] ", e);
  41. return NextResponse.json(prettyObject(e));
  42. }
  43. }
  44. export const GET = handle;
  45. export const POST = handle;
  46. export const runtime = "edge";
  47. export const preferredRegion = [
  48. "bom1",
  49. "cle1",
  50. "cpt1",
  51. "gru1",
  52. "hnd1",
  53. "iad1",
  54. "icn1",
  55. "kix1",
  56. "pdx1",
  57. "sfo1",
  58. "sin1",
  59. "syd1",
  60. ];
  61. async function request(req: NextRequest, apiKey: string) {
  62. const controller = new AbortController();
  63. let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL;
  64. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Google, "");
  65. if (!baseUrl.startsWith("http")) {
  66. baseUrl = `https://${baseUrl}`;
  67. }
  68. if (baseUrl.endsWith("/")) {
  69. baseUrl = baseUrl.slice(0, -1);
  70. }
  71. console.log("[Proxy] ", path);
  72. console.log("[Base Url]", baseUrl);
  73. const timeoutId = setTimeout(
  74. () => {
  75. controller.abort();
  76. },
  77. 10 * 60 * 1000,
  78. );
  79. const fetchUrl = `${baseUrl}${path}${
  80. req?.nextUrl?.searchParams?.get("alt") === "sse" ? "?alt=sse" : ""
  81. }`;
  82. console.log("[Fetch Url] ", fetchUrl);
  83. const fetchOptions: RequestInit = {
  84. headers: {
  85. "Content-Type": "application/json",
  86. "Cache-Control": "no-store",
  87. "x-goog-api-key":
  88. req.headers.get("x-goog-api-key") ||
  89. (req.headers.get("Authorization") ?? "").replace("Bearer ", ""),
  90. },
  91. method: req.method,
  92. body: req.body,
  93. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  94. redirect: "manual",
  95. // @ts-ignore
  96. duplex: "half",
  97. signal: controller.signal,
  98. };
  99. try {
  100. const res = await fetch(fetchUrl, fetchOptions);
  101. // to prevent browser prompt for credentials
  102. const newHeaders = new Headers(res.headers);
  103. newHeaders.delete("www-authenticate");
  104. // to disable nginx buffering
  105. newHeaders.set("X-Accel-Buffering", "no");
  106. return new Response(res.body, {
  107. status: res.status,
  108. statusText: res.statusText,
  109. headers: newHeaders,
  110. });
  111. } finally {
  112. clearTimeout(timeoutId);
  113. }
  114. }