AI AI Club
← 返回文章列表

Node.js / TypeScript 实战范例:在 Next.js 服务端高效调用 Gemini

前端全栈工程师必看!基于 @google/generative-ai 官方包,使用现代 TypeScript 编写健壮的 Next.js 服务端路由与异步接口处理范例。

一、安装官方 npm 依赖包

npm install @google/generative-ai

二、Next.js API Route 完整端点代码

import { GoogleGenerativeAI } from "@google/generative-ai";
import { NextResponse } from "next/server";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);

export async function POST(req: Request) {
const { prompt } = await req.json();
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
return NextResponse.json({ text: response.text() });
}
使用现代 TypeScript 类型定义,具备完整的代码智能补全与出色的并发处理能力。

联系我们

会员开通、订单问题或合作咨询,欢迎联系。

QQ1192214187
邮箱winky20000401@gmail.com