google.ts 3.1 KB

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