


Creating a Chatbot with JavaScript and Gemini AI: creating the backend
Save! o
Continuing the creation of our chatbot with Javascript and Gemini AI, we will add the "backend" of the project. Last time we created the frontend, with HTML, CSS and Javascript, where we guaranteed that the user interface will reflect a conversation between the user and the chatbot.
Now we need to create a server, configuring a route with express.js to communicate with the Gemini API. Let's go!
Installing project dependencies
Well, we're going to need express.js, the Google Gemini SDK and to protect our API key I'm going to install dotenv to work with environment variables.
npm install @google/generative-ai express dotenv
Now we are ready to create our server adopting best practices such as using local environment variables to protect private data.
To do this, we will create a file in the project root folder called server.js. In this file we will start by importing the dependencies and configuring the necessary resources.
const express = require("express"); require("dotenv").config(); const { GoogleGenerativeAI } = require("@google/generative-ai"); const app = express(); const port = 3000; const genAI = new GoogleGenerativeAI(process.env.GOOGLE_GEMINI_API_KEY); app.use(express.static("public")); app.use(express.json());
This code configures express to serve static files from the "public" folder and accepts requests with JSON payload. That's why we put the index.html, styles.css and script.js files in this folder. We also configured the application to run on port 3000.
We use the @google/generative-ai library to integrate the Gemini API, authenticating it with a key stored in an environment variable called GOOGLE_GEMINI_API_KEY.
But where do we get this API Key? That's what we're going to find out now.
Gemini API Key
Obtaining the key
To get a Gemini API key, I recommend that you are logged into an "@gmail.com" account. After that, access this link and you will see a screen like this:
Click the "Create API key" button, indicate a project in which you will use this key and you're done. Your key will appear below and you will be able to view it and even copy it to take the next step.
Protecting your API key
Now in your project, create a file with the name .env.local or just .env in the root folder of your project. In this file put your API key as follows:
GOOGLE_GEMINI_API_KEY="sua-chave-vai-aqui"
Now save your file and that's it. If you did the previous step correctly, your API key will be working.
PS: pay attention to the plan that appears in your API key. Gemini offers a free plan with a limited amount of tokens that your key can return. If you want a greater amount of tokens, consider subscribing to a paid plan. We will use the free plan, which, although limited, will allow us to exchange some messages with the chatbot.
Creating the /chat route
Now with the dependencies configured and the API key in hand, let's open the doors of possibilities of what we can do with artificial intelligence.
In the server.js file we will create the /chat route:
npm install @google/generative-ai express dotenv
Our route is of the POST type, as you will receive a message in the body, precisely the message from the user who will interact with the chat. So, with this message we use a little defensive programming (it doesn't hurt anyone to be careful lol) and check that we don't have a message. If we don't, an error is returned as a response and a message is thrown.
If we have the message, then we will send it as a prompt for the model we choose, as follows:
const express = require("express"); require("dotenv").config(); const { GoogleGenerativeAI } = require("@google/generative-ai"); const app = express(); const port = 3000; const genAI = new GoogleGenerativeAI(process.env.GOOGLE_GEMINI_API_KEY); app.use(express.static("public")); app.use(express.json());
As this communication is an asynchronous process, we will use try/catch to handle the response. First I define the Gemini model that will be used (you can check a list of models at this link). In this case I opted for gemini-1.5-flash.
The second step is to start the chat. So with model.startChat() I can start communication with Gemini, configuring the maximum number of tokens I want in the response (in this case 100 tokens per response).
Now we wait for this response after sending the message to the model with chat.sendMessage(message). When we have the response, we will return it to the person who made the request, converting the text format returned by the model to JSON.
And last but not least, if we have an error we can use it within catch to throw this error in the console, and also returning a status 500, making life easier for the client who is consuming this "mini api". Beauty?
Now we just need to indicate where our "mini api" will run with the code snippet below:
GOOGLE_GEMINI_API_KEY="sua-chave-vai-aqui"
Our api will run on the port we specified at the beginning. The complete server.js code is shown below:
app.post("/chat", async (req, res) => { const { message } = req.body; if (!message) { return res.status(400).json({ error: "Mensagem não pode estar vazia." }); } //... });
Testing the chatbot
Now the most awaited moment has arrived, to test our chatbot. To do this, let's open a terminal and type the following command:
try { const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash", }); const chat = model.startChat({ history: [], generationConfig: { maxOutputTokens: 100 }, }); const result = await chat.sendMessage(message); res.json({ response: result.response.text() }); } catch (error) { console.error(error); res.status(500).json({ error: "Erro ao processar mensagem." }); }
You should receive the following message in the terminal after running this command:
app.listen(port, () => { console.log(`Servidor rodando em http://localhost:${port}`); });
Now by accessing the url http://localhost:3000 and writing a message in the input and pressing the send button, the AI responds to your message and it is shown on the screen.
Very cool, right?
Conclusion
With this we finish creating a chatbot using JavaScript and the Google Gemini API. We saw how to create the frontend from scratch, apply styles, manipulate the DOM. We created a server with express.js, used the Gemini API, configured a POST route to communicate with the application client and were able to talk to the AI through our own interface, developed by ourselves.
But that's not all you can do. We can customize and configure this chatbot for different tasks, from being a language assistant, to a virtual teacher who answers your questions about mathematics or programming, it will depend on your creativity.
Turning an AI into a personalized assistant involves training the model, more about the way you want it to respond and behave than about the code itself.
We'll explore some of this in a future article.
See you then!
The above is the detailed content of Creating a Chatbot with JavaScript and Gemini AI: creating the backend. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion
