从认证到 API 调用的实操指南,展示如何在 Node.js 应用中集成 Google Gemini,附代码示例。
我是 Arindam Majumder,来自印度的软件工程师。我对使用 Next.js、JavaScript、ReactJs 和 Python 开发软件解决方案感兴趣,并撰写和开发(开源)相关内容。
Twitter: twitter.com/Arindam_1729 Blog: dev.to/arindam_1729 YouTube: youtube.com/@Arindam_1729 LinkedIn: linkedin.com/in/arindam2004 GitHub: github.com/Arindam200
📧 订阅我的通讯。
作为一个普通人,我喜欢玩电子游戏。玩了各种游戏后,我可以说我购买的游戏物有所值。因为开发者投入了大量时间和精力来打造完美的游戏并呈现最精致的画面。试试 Run 3,你就明白我的意思了。
生成式 AI 在过去一年成为科技界的热门话题。每个人都在用它构建酷炫的项目。Google 有自己的生成式 AI,叫做 Gemini。
最近,Google 为 Gemini 开发者推出了 API。这附带了多个库和框架,开发者可以将其集成到自己的应用中。
在本文中,我们将构建一个简单的 Node.js 应用并集成 Google Gemini。我们会使用 Google Gemini SDK。
那么,不再拖延,让我们开始吧!
Google Gemini 是由 Google AI 开发的强大且多面的 AI 模型。Gemini 不仅处理文本;它可以理解并跨越代码、音频、图像和视频等各种格式运行。这为你的 Node.js 项目打开了令人兴奋的可能性。
要启动我们的项目,我们需要设置 Node.js 环境。所以,让我们创建一个 node 项目。在终端运行以下命令。
npm init
这会初始化一个新的 Node.js 项目。
现在,我们需要安装项目的必需依赖。
npm install express body-parser @google/generative-ai dotenv
这将安装以下包:
接下来,我们将创建一个 .env 文件来安全存储我们的敏感信息,如 API 凭证。
//.env
API_KEY=YOUR_API_KEY
PORT=3000
在使用 Gemini 之前,我们需要从 Google Developers Console 设置 API 凭证。为此,我们需要在 Google 账户上注册并创建 API 密钥。
登录后,前往 https://makersuite.google.com/app/apikey。你会看到类似这样的界面:
然后点击"Create API key"按钮。这将生成一个唯一的 API 密钥,我们将用它来验证对 Google Generative AI API 的请求。
要测试你的 API,可以运行以下 Curl 命令:
curl \
-H 'Content-Type: application/json' \
-d '{"contents":[{"parts":[{"text":"Write a story about a magic backpack"}]}]}' \
-X POST https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY
将 YOUR_API_KEY 替换为我们之前获得的实际 API 密钥。
获得 API 密钥后,我们将用它更新 .env 文件。
现在,我们将在根目录创建一个 index.js 文件并设置一个基础 express 服务器。查看以下代码:
const express = require("express");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const port = process.env.PORT;
app.get("/", (req, res) => {
res.send("Hello World");
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
这里我们使用 "dotenv" 包来从 .env 文件访问 PORT 号。
在项目顶部,我们使用 dotenv.config() 加载环境变量,使其在整个文件中可访问。
在这一步中,我们将添加一个 start 脚本到 package.json 文件,以便轻松运行我们的项目。
所以,将以下脚本添加到 package.json 文件:
"scripts": {
"start": "node index.js"
}
package.json 文件应该看起来像这样:
要检查所有内容是否正常工作,让我们使用以下命令运行项目:
npm run start
这将启动 Express 服务器。现在如果我们访问 http://localhost:3000/ 这个 URL,我们会得到:
太好了!项目设置完成并且工作完美。接下来,我们将在下一节中将 Gemini 添加到我们的项目中。
要将 Gemini 添加到我们的项目,我们将创建一个 /generate 路由,在这里我们与 Gemini AI 进行通信。
为此,将以下代码添加到 index.js 文件:
const bodyParser = require("body-parser");
const { generateResponse } = require("./controllers/index.js");
//middleware to parse the body content to JSON
app.use(bodyParser.json());
app.post("/generate", generateResponse);
这里我们使用 body-parser 中间件将内容解析为 JSON 格式。
现在,我们将创建一个 controller 文件夹,在其中创建一个 index.js 文件。这里我们将创建一个新的控制器函数来处理上面代码中声明的 generate 路由。
const { GoogleGenerativeAI } = require("@google/generative-ai");
const dotenv = require("dotenv");
dotenv.config();
// GoogleGenerativeAI required config
const configuration = new GoogleGenerativeAI(process.env.API_KEY);
// Model initialization
const modelId = "gemini-pro";
const model = configuration.getGenerativeModel({ model: modelId });
这里我们通过传递来自环境变量的 API 密钥来为 Google Generative AI API 创建一个配置对象。
然后,我们通过向配置对象的 getGenerativeModel 方法提供模型 ID("gemini-pro")来初始化模型。
我们也可以根据我们的方便来配置模型参数。
这些参数值控制模型如何生成响应。
const generationConfig = {
stopSequences: ["red"],
maxOutputTokens: 200,
temperature: 0.9,
topP: 0.1,
topK: 16,
};
const model = configuration.getGenerativeModel({ model: modelId, generationConfig });
我们可以使用安全设置来防止得到有害的响应。默认情况下,安全设置配置为在各个维度阻止中到高概率不安全的内容。
以下是一个示例:
const { HarmBlockThreshold, HarmCategory } = require("@google/generative-ai");
const safetySettings = [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
},
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
];
const model = genAI.getGenerativeModel({ model: "MODEL_NAME", safetySettings });
通过这些安全设置,我们可以通过最小化有害内容生成的可能性来增强安全性。
要跟踪对话历史,我们创建了一个数组 history 并将其从控制器文件导出:
export const history = [];
现在,我们将编写一个控制器函数 generateResponse 来处理生成路由(/generate)并生成对用户请求的响应。
/**
* Generates a response based on the given prompt.
* @param {Object} req - The request object.
* @param {Object} res - The response object.
* @returns {Promise} - A promise that resolves when the response is sent.
*/
export const generateResponse = async (req, res) => {
try {
const { prompt } = req.body;
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();
console.log(text);
history.push(text);
console.log(history);
res.send({ response: text });
} catch (err) {
console.error(err);
res.status(500).json({ message: "Internal server error" });
}
};
这里我们从请求体中取出 prompt,并使用 model.generateContent 方法基于 prompt 生成响应。
为了跟踪响应,我们将响应推送到 history 数组。
现在,我们将创建一个路由来检查我们的响应历史。这个端点返回 history 数组。
将简单的代码添加到 ./index.js 文件。
app.get("/generate", (req, res) => {
res.send(history);
});
现在,我们需要检查我们的应用是否正常工作!
让我们使用以下命令运行我们的项目:
npm run start
没有错误!感谢天主!:)它工作正确。
接下来,我们将使用 Postman 发起 Post 请求来验证我们的控制器函数。
我们将向 http://localhost:3000/generate 发送一个 POST 请求,带有以下 JSON 负载:
{
"prompt": "Write 3 Javascript Tips for Beginners"
}
我们得到了我们的响应:
{
"response": "1. **Use console.log() for Debugging:**\n - console.log() is a useful tool for debugging your JavaScript code. It allows you to inspect the values of variables and expressions, and to see how your code is executing. This can be especially helpful when you encounter errors or unexpected behavior in your program.\n\n2. **Learn the Basics of Data Types:**\n - JavaScript has several built-in data types, including strings, numbers, booleans, and objects. Understanding the properties and behaviors of each data type is crucial for writing effective code. For instance, strings can be manipulated using string methods, while numbers can be used in mathematical operations.\n\n3. **Use Strict Mode:**\n - Strict mode is a way to opt-in to a restricted and secure subset of JavaScript. It helps you to write more secure and reliable code, as it throws errors for common mistakes that would otherwise go unnoticed in regular JavaScript mode. To enable strict mode, simply add \"use strict;\" at the beginning of your JavaScript file or module."
}
太好了!我们的 Gemini AI 集成按预期工作!
此外,我们可以在 http://localhost:3000/generate 访问历史端点来查看对话历史。
这样,我们已经将 Gemini AI 集成到了我们的 Node.js 应用中。在接下来的文章中,我们将探索更多 Gemini AI 的用例。
在那之前,保持关注!
如果你觉得这篇博客文章有帮助,请考虑与其他可能受益的人分享。你也可以关注我以获取更多关于 Javascript、React 和其他 web 开发主题的内容。
要赞助我的工作,请访问:Arindam 的赞助页面,并浏览各种赞助选项。
在 Twitter、LinkedIn、Youtube 和 GitHub 上与我联系。
感谢你的阅读 :)