google.ts 3.1 KB

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